OK, I already know the explode way: $keywords='One Two Three'; $array=explode(' ',$keywords); // I will have array of: 'One', 'Two', 'Three' PHP: But incase Two or more word is double quoted $keywords='"One Two" Three'; //$array=??? // I will have array of 2 element: 'One Two', 'Three' PHP: How can I do that?
In the array they need to be seperated by a common factor. Eg: $keywords = 'One - Two - Three'; $array = explode('-', $keywords); PHP: If your needing 'One Two' and 'Three' you could seperate like so: $array = '"One Two" - Three'; PHP: But that would woutput "One Two" Three.
Oh, I Just want to parse the key word like Google does. A string: "One Two" Three will be broken into One Two, Three. I guess some Regular Expression must be used? Can somebody help?
Yes, regex is the answer Try this: $test = '"This is" a test'; $MyArray = array(); $MyArray = preg_split( "/[\W]{1,4}/", $test ); echo "<pre>"; print_r( $MyArray ); echo "</pre>"; PHP: Brew
Not sure if there's a way to do that with a single regular expression, but this does work: <?php $query = 'This is what "I have" been "searching for!"'; $keywords = array(); while (preg_match('/(?:"([^"]+)"|([^\s]+))/', $query, $quotes)) { $keywords[] = trim(isset($quotes[2]) ? $quotes[2] : $quotes[1]); $query = str_replace($quotes[0], null, $query); } echo '<pre>' . print_r($keywords, true) . '</pre>'; ?> PHP:
Hi goldensea80 Just out of curiosity what string are you passing to my code? On my system the code outputs this: Array ( [0] => [1] => This [2] => is [3] => a [4] => test ) Brew EDIT: Sorry, just re-read your initial question more closely... Nico is the winner!
He doesn't want to split the string on spaces if there are double quotes around it. Like Google does. This. $keywords='"One Two" Three'; PHP: Sould become this: Array ( [0] => One two [1] => Three ) Code (markup):