Jay
Jay

Reputation: 1104

php explode something into array, but using values in between

I have a string I want to clean up and put into an array so that I can search through it in mysql.


// Here's one example of what the string might have:
$string1 = "(1) *value1* *value2*; (2) *value3* *value4* *value5*; (3) *value6*";
// And here's another possibility:
$string2 = "*value1* *value2* *value3* *value4*";

// I want to remove all the "(#)" stuff, and explode all the values into an array
// This is what I have so far:
// $string can be like the examples $string1 or $string2

$string_clean = str_replace("* *","",trim(preg_replace("/\((\d)\)/i", "", $string)));
$my_array = explode('*', trim($string_clean, '*'));

However, this is what I'm getting:

Array ( [0] => value1 [1] => [2] => value2 [3] => [4] => value3 [5] => [6] => value4 [7] => [8] => value5 ) 

I suppose I could just find a function to remove all empty items from the array, but I'm wondering if there's a more effective way to do this?

Upvotes: 1

Views: 641

Answers (1)

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99921

You need preg_match_all():

preg_match_all('#\*([^*]+)\*#', $string, $matches);
$result = $matches[1];
// $result is array('value1', 'value2', ...)

This will find all *something* and return the strings between the *.

Upvotes: 3

Related Questions