-
preg_match question
Hi Guys,
I need to extract phrases / words into an array from a string. The current code I am using is shown below, but it doesn't work as intended.
Here is the output i would like to see from the folowing string:
STRING:
Code:
"technical writer" "documentation manager" "technical author"
Output should be:
PHP Code:
<?php
Array
(
[0] => technical writer
[1] => documentation manager
[2] => technical author
)
?>
STRING:
Code:
"technical writer" and "documentation manager" and "technical author"
Output should be:
PHP Code:
<?php
Array
(
[0] => technical writer
[1] => and
[2] => documentation manager
[3] => and
[4] => technical author
)
?>
-
I am not so experienced with regular expressions, but I have come up with this.
Only problem is that it puts the starting and ending space also in the array value.
PHP Code:
preg_match_all('/[a-z\s]+/i','"technical writer" and or "documentation manager" and "technical author"',$matches);
echo '<pre>';
print_r($matches);
echo '</pre>';
Outputs:
PHP Code:
Array
(
[0] => Array
(
[0] => technical writer
[1] => and or
[2] => documentation manager
[3] => and
[4] => technical author
)
)
So you have to look for yourself how to fix the expression, to get rid of the spaces. Also you have to modify it to your needs offcourse.
-
Simple answer: Dont preg_match, preg_split.
PHP Code:
$results = preg_split('~\"(.*?)\"~',$test,-1,PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
As far as removing the spaces, array_map('trim',$results);