Jamie Bicknell Jamie Bicknell - 3 months ago 7
PHP Question

Extract keywords/tags from string using Preg_match_all

I have the following code

$str = "keyword keyword 'keyword 1 and keyword 2' another 'one more'".'"another keyword" yes,one,two';

preg_match_all('/"[^"]+"|[^"\' ,]+|\'[^\']+\'/', $str, $matches);

echo "<pre>"; print_r($matches); echo "</pre>";

Where I want it to extract keywords from a string, and keep those wrapped within single or double quotes together, this above code works OK, but it returns the values with the quotes in it. I know I can remove these via str_replace or similar, but I'm really looking for a way to solve this via the preg_match_all function.


[0] => Array
[0] => keyword
[1] => keyword
[2] => 'keyword 1 and keyword 2'
[3] => another
[4] => 'one more'
[5] => "another keyword"
[6] => yes
[7] => one
[8] => two


Also, I think my regex is a little be soppy, so any suggestions for a better would would be good :)

Any suggestions / help would be greatly appreciated.


You've almost got it; you just need to use lookarounds to match the quotes: