PHP爆炸功能
问题描述:
我想让用户输入标签:
windows linux mac os x
windows linux "mac os x"
然后将它们按空格分开,但也将 mac os x识别为一个整体。
and then split them up by white space but also recognizing "mac os x" as a whole word.
是否可以将explode函数与其他函数结合使用?
Is this possible to combine the explode function with other functions for this?
必须有一种方法。
答
只要引号内不能有引号(例如, foo bar
是不允许的),则可以使用正则表达式执行此操作,否则需要一个完整解析器。
As long as there can't be quotes within quotes (eg. "foo\"bar"
isn't allowed), you can do this with a regular expression. Otherwise you need a full parser.
应该这样做:
function split_words($input) {
$matches = array();
if (preg_match_all('/("([^"]+)")|(\w+)/', $input, $reg)) {
for ($ii=0,$cc=count($reg[0]); $ii < $cc; ++$ii) {
$matches[] = $reg[2][$ii] ? $reg[2][$ii] : $reg[3][$ii];
}
}
return $matches;
}
用法:
$input = 'windows linux "mac os x"';
var_dump(split_words($input));