我有一个字符串像
$string = 'Some of "this string is" in quotes';
我想要得到字符串中所有单词的数组我可以通过
得到$words = explode(' ', $string);
但是我不想用引号分隔单词所以理想情况下结束数组将是
array ('Some', 'of', '"this string is"', 'in', 'quotes');
有人知道我该怎么做吗?
您可以使用:
$string = 'Some of "this string is" in quotes';
$arr = preg_split('/("[^"]*")|'h+/', $string, -1,
PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
print_r ( $arr );
输出:Array
(
[0] => Some
[1] => of
[2] => "this string is"
[3] => in
[4] => quotes
)
RegEx分手
("[^"]*") # match quoted text and group it so that it can be used in output using
# PREG_SPLIT_DELIM_CAPTURE option
| # regex alteration
'h+ # match 1 or more horizontal whitespace
你可以用另一种方式来代替这种方式,也就是匹配。匹配要比拆分容易得多。
所以使用正则表达式:/[^'s]+|".*?"/
和preg_match_all
。
您可以使用regex:
获得匹配值,而不是分割值。/"[^"]+"|'w+/g
匹配:
-
"[^"]+"
-引号之间的字符", -
'w+
-字符集(A-Za-z_0-9),
我认为你可以这样使用正则表达式:
/("[^"]*")|('S+)/g
可以用$2