Search code examples
phppreg-split

Split string after a letter


I am trying to use preg_split as below:

$tarea = "13.3R4.2";
$keywords = preg_split("/[0-9]*.[0-9][a-zA-Z]/", $tarea);
print_r ($keywords);

I am unable to capture the array [0] value. Below is the output:

Array ( [0] => [1] => 4.2 ) 

I want to capture both the indexes of the array. I am not sure what mistake I am doing here.

The output I expect is:

Array ( [0] => 13.3R[1] => 4.2 )

Solution

  • I think you are misunderstanding the purpose of preg_split(). It splits a string on the specified separator, meaning it's not designed to return the separator. You want to be using preg_match() to return matched substrings:

    $tarea = "13.3R4.2";
    preg_match_all("/[0-9]+\.[0-9][a-z]?/i", $tarea, $matches);
    print_r($matches);