Maddy
Maddy

Reputation: 53

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 )

Upvotes: 1

Views: 169

Answers (2)

Maddy
Maddy

Reputation: 53

Below code solved the issue:

$tarea = "13.3R4.2";
$keywords = preg_split('/(\d*\.\d\w?)/',$tarea, -1, PREG_SPLIT_DELIM_CAPTURE |     PREG_SPLIT_NO_EMPTY);
print_r ($keywords);

Output:

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

Thank you all for the great help!!!

Upvotes: 1

miken32
miken32

Reputation: 42724

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);

Upvotes: 1

Related Questions