Home Ask Login Register

Developers Planet

Your answer is one click away!

Maddy February 2016

PHP preg_split()

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. Kindly help!!

The output I expect is:

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



miken32 February 2016

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

Maddy February 2016

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


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

Thank you all for the great help!!!

Post Status

Asked in February 2016
Viewed 3,519 times
Voted 14
Answered 2 times


Leave an answer

Quote of the day: live life