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?

link|improve this question

If your values don't contain spaces you could str_replace() away * and ;, preg_repalce() away (#) and then explode() on " " to get all the values. – Ben L. Feb 1 '11 at 13:39
feedback

1 Answer

up vote 2 down vote accepted

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 *.

link|improve this answer
Thanks man! I just got a funny result with array within an array though – Jay Feb 1 '11 at 13:41
Yes, the result is in $matches[1], as I said, not in $matches :-) – arnaud576875 Feb 1 '11 at 13:42
Array ( [0] => Array ( [0] => value1 [1] => value2 [2] => value3 [3] => value4 [4] => value5 ) [1] => Array ( [0] => value1 [1] => value2 [2] => value3 [3] => value4 [4] => value5 ) ) – Jay Feb 1 '11 at 13:43
Oooh haha my bad :) thanks so much!! – Jay Feb 1 '11 at 13:43
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.