1

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?

1
  • 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. Commented Feb 1, 2011 at 13:39

1 Answer 1

3

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

3
  • Thanks man! I just got a funny result with array within an array though Commented Feb 1, 2011 at 13:41
  • Yes, the result is in $matches[1], as I said, not in $matches :-) Commented Feb 1, 2011 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 ) ) Commented Feb 1, 2011 at 13:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.