Php 简单正则表达式中同一行上存在多个匹配项的问题
我有一个关于正则表达式的基本问题。我正在尝试匹配和替换如下URL:Php 简单正则表达式中同一行上存在多个匹配项的问题,php,regex,string,Php,Regex,String,我有一个关于正则表达式的基本问题。我正在尝试匹配和替换如下URL: http://mydomain.com/image/13/imagetitle.html 对此,我使用以下表达式: /mydomain.com(.*)image\/(\d+)\/(.*).html/ 此模式基本上可以正常工作,但当多个引用出现在同一行上时,它不起作用。所以这是可行的: This is my own image: http://mydomain.com/image/13/imagetitle.html 在跨线
http://mydomain.com/image/13/imagetitle.html
对此,我使用以下表达式:
/mydomain.com(.*)image\/(\d+)\/(.*).html/
此模式基本上可以正常工作,但当多个引用出现在同一行上时,它不起作用。所以这是可行的:
This is my own image: http://mydomain.com/image/13/imagetitle.html
在跨线包含多个引用时,它也可以工作:
This is my own image: http://mydomain.com/image/13/imagetitle.html
Yet I recommend this one as well: image: http://mydomain.com/image/15/imagetitle2.html
两个引用均匹配,并已正确替换。但是,它仅在同一行上有两个匹配项时替换第一个匹配项:
This is my own image: http://mydomain.com/image/13/imagetitle.html, yet I recommend this one as well: image: http://mydomain.com/image/15/imagetitle2.html
如何确保所有匹配项都被替换,而不考虑新行?我也没有遇到问题。但从正则表达式来看,你的问题很可能是贪婪
(.*)
尽可能匹配。如果两个URL在同一行上,它将同时捕获它们。因此,通常需要使用(.*?
,或者应用ungreediness/U
标志
但在你的情况下,我建议你只需让比赛更加具体:
/mydomain.com(\S*)image\/(\d+)\/(\S*).html/
这里的
\S
将只匹配任何非空白的内容,因为这是最确定的URL应该拆分的地方。作为替代方案,您可以使用更具体的字符类,如([\w/?&%=-]*)
,而不是那里的*?
。您的模式正在工作。我已经用foll代码对其进行了测试:
$data = "This1 is my own image: http://mydomain.com/image/13/imagetitle.html, yet I recommend this one as well: image: http://mydomain.com/image/15/imagetitle2.html
This2 is my own image: http://mydomain.com/image/13/imagetitle.html, yet I recommend this one as well: image: http://mydomain.com/image/15/imagetitle2.html
This3 is my own image: http://mydomain.com/image/13/imagetitle.html, yet I recommend this one as well: image: http://mydomain.com/image/15/imagetitle2.html
This4 is my own image: http://mydomain.com/image/13/imagetitle.html, yet I recommend this one as well: image: http://mydomain.com/image/15/imagetitle2.html
";
echo preg_replace('/mydomain.com(.*)image\/(\d+)\/(.*).html/', 'replaced one', $data);
你能粘贴用来替换的代码吗?实际上,从preg_replace()函数的角度来看,br/>不是一个换行符。这两个例子都被视为单线主题。如果你展示你的替换代码,它会更清晰。@Kel:我很确定实际文本在那个位置有一个换行符,但是OP错误地认为,当他发布问题时,换行符会被规范化为一个空格,所以把它改成了
。正如您所指出的,如果那里真的有一个
,他就不会有这个问题了。谢谢您,这非常有效!这确实是一个贪婪的问题,我完全按照你的建议使用了“特定匹配”的完整规则。