如何匹配a";标签";使用正则表达式的列表&;PHP
我有一个表单输入字段,它接受来自用户的多个“标签”,有点像这个站点上的标签!例如,用户可以输入如下内容:如何匹配a";标签";使用正则表达式的列表&;PHP,php,regex,Php,Regex,我有一个表单输入字段,它接受来自用户的多个“标签”,有点像这个站点上的标签!例如,用户可以输入如下内容: php mysql regex …分离多个标记会很好&很简单,因为我可以在空格上分解()。我最终会: array('php', 'mysql', 'regex') 但是,由于用户可以用逗号或逗号分隔标记,所以事情变得稍微复杂一些 空格&对多单词标记使用双引号 因此,用户还可以输入: php "mysql" regex, "zend framework", another "a, tag
php mysql regex
…分离多个标记会很好&很简单,因为我可以在空格上分解()。我最终会:
array('php', 'mysql', 'regex')
但是,由于用户可以用逗号或逗号分隔标记,所以事情变得稍微复杂一些
空格&对多单词标记使用双引号
因此,用户还可以输入:
php "mysql" regex, "zend framework", another "a, tag with punc $^&!)(123 *note the comma"
所有这些都是有效的。这应产生:
array('php', 'mysql', 'regex', 'zend framework', 'another', 'a, tag with punc $^&!)(123 *note the comma')
我不知道如何编写一个正则表达式,它首先匹配双引号中的所有内容,然后分解逗号或空格上的字符串&最后匹配其他所有内容。我想我会用preg_match_all()来做这个
谁能给我指一下正确的方向!?非常感谢。试试这个正则表达式。我用你的绳子测试了它,它正确地拉出了各个标签:
("([^"]+)"|\s*([^,"\s]+),?\s*)
此代码:
$string = 'php "mysql" regex, "zend framework", another "a, tag with punc $^&!)(123 *note the comma"';
$re = '("([^"]+)"|\s*([^,"\s]+),?\s*)';
$matches = array();
preg_match_all($re, $string, $matches);
var_dump($matches);
为我产生了以下结果:
array(3) {
[0]=>
array(6) {
[0]=>
string(4) "php "
[1]=>
string(7) ""mysql""
[2]=>
string(8) " regex, "
[3]=>
string(16) ""zend framework""
[4]=>
string(9) " another "
[5]=>
string(44) ""a, tag with punc $^&!)(123 *note the comma""
}
[1]=>
array(6) {
[0]=>
string(0) ""
[1]=>
string(5) "mysql"
[2]=>
string(0) ""
[3]=>
string(14) "zend framework"
[4]=>
string(0) ""
[5]=>
string(42) "a, tag with punc $^&!)(123 *note the comma"
}
[2]=>
array(6) {
[0]=>
string(3) "php"
[1]=>
string(0) ""
[2]=>
string(5) "regex"
[3]=>
string(0) ""
[4]=>
string(7) "another"
[5]=>
string(0) ""
}
}
希望能有所帮助。非常感谢!明天我会在我的应用程序中第一件事就是试用它,所以我会向你汇报并让你知道!