我正在尝试匹配一段文本中的引用字符串,并允许其中的转义引号。我在在线测试仪中尝试了这个正则表达式,它运行得很好。但是,当我在preg_match_all中尝试时,它会在第一个转义字符串处失败。
以下是代码:
$parStr = 'title="My Little Website"
year="2007"
description="Basic website with ..."
tech="PHP, mySQL"
link="<a href=\"http://test.com\">test.com</a>"
';
$matches = array();
preg_match_all('/(\w+)\s*=\s*"(([^\\"]*(\\.)?)*)"/', $parStr, $matches, PREG_SET_ORDER); // Match[4][0] is 'link="<a href=\"'
它在最后一场比赛中失败,只匹配到第一个转义报价。当我在http://www.regexplanet.com/simple/index.html尝试这个表达时,它完美无缺。
正则表达式的相关部分是:
"(([^\\"]*(\\.)?)*)"
哪个应该吃掉所有文本,直到转义的报价或报价,然后吃掉一个可选的转义报价,哪个过程重复0次或更多次,直到找到未转义的报价,其中匹配完成。
为什么这不适用于php?为什么它不起作用,应该如何解决?
答案 0 :(得分:2)
我不知道为什么它不能用于某个特定版本的php,但是使用非贪婪匹配的想法,我想出了这个字符串可以工作:
"(.*?[^\\\])"
它会非常贪婪地匹配所有内容,直到它遇到一个没有转义字符的dbl-quote。出于某些特殊原因,需要三个反斜杠或者php抱怨无法比拟的支架。我认为它的存在需要在括号之前加上反斜杠,但我不确定。任何人都可以确认为什么需要三个反斜杠?
/编辑空白限制
答案 1 :(得分:0)
我在Linux Fedora PHP 5.2.6上尝试过它似乎工作正常。输出是:
[wally@zf ~]$ php -f z.php
title="My Little Website"
year="2007"
description="Basic website with ..."
tech="PHP, mySQL"
link="<a href=\"http://test.com\">test.com</a>"
答案 2 :(得分:0)
这样怎么样?
preg_match_all('/(\w+)\s*=\s*"((?:.*?\"?)*)"/', $parStr, $matches, PREG_SET_ORDER);
它给我这样的
[1] => link
[2] => <a href=\"http://test.com\">test.com</a>
在[]中,一切都被认为是单个字符,
代表[^\\"]
,并不意味着EXCEPT \"
,意思是EXCEPT \
和EXCEPT "
更新
preg_match_all('/(\w+)\s*=\s*"((?:[^\\\]*?(?:\\\")?)*?)"/', $parStr, $matches, PREG_SET_ORDER);
源字符串,示例
$ parStr ='title =“我的小网站” 一年= “2007” description =“基本网站......” tech =“PHP,mySQL”tech =“PHP,mySQL” link =“http://test.com \”&gt; test.com“link =”http://test.com \“&gt; test.com”tech =“PHP,mySQL” “;
<强>匹配强>,
Array
(
[0] => Array
(
[0] => title="My Little Website"
[1] => title
[2] => My Little Website
)
[1] => Array
(
[0] => year="2007"
[1] => year
[2] => 2007
)
[2] => Array
(
[0] => description="Basic website with ..."
[1] => description
[2] => Basic website with ...
)
[3] => Array
(
[0] => tech="PHP, mySQL"
[1] => tech
[2] => PHP, mySQL
)
[4] => Array
(
[0] => tech="PHP, mySQL"
[1] => tech
[2] => PHP, mySQL
)
[5] => Array
(
[0] => link="<a href=\"http://test.com\">test.com</a>"
[1] => link
[2] => <a href=\"http://test.com\">test.com</a>
)
[6] => Array
(
[0] => link="<a href=\"http://test.com\">test.com</a>"
[1] => link
[2] => <a href=\"http://test.com\">test.com</a>
)
[7] => Array
(
[0] => tech="PHP, mySQL"
[1] => tech
[2] => PHP, mySQL
)
)
就个人而言,我觉得用正则表达式解析HTML,并不是真的很喜欢,但是我没有看到任何其他选项建议你,所以它只是一种快速而肮脏的方式。对于大项目或大文件,我建议你找到一个真正的解析器。