在PHP中正则表达式中转义引号时出错
我是PHP新手,试图用下面的代码中的google.com替换URL模式。在PHP中正则表达式中转义引号时出错
$textStr = "Test string contains http://foo.com/more_(than)_one_(parens)
http://foo.com/blah_(wikipedia)#cite-1
http://foo.com/blah_(wikipedia)_blah#cite-1
http://foo.com/unicode_(?)_in_parens
http://foo.com/(something)?after=parens
more urls foo.ca/me some other text";
$pattern = '(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)((?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))*)';
$textStr = preg_replace($pattern, "google.com", $textStr);
echo $textStr;
我发现正则表达式模式在http://daringfireball.net/2010/07/improved_regex_for_matching_urls但我一直没能成功逃脱单引号,双引号中的格局。
目前我得到的消息 - 警告:的preg_replace()未知的修饰词“\” 但我用斜线(),以逃避{单引号};:\'”
能有人帮我上面?
在首位preg_replace
你必须划定你的正常快递通过/
离子,如:
/\b((?:https: ... etc etc)/
其次,因为你/
,你必须使用反斜线任何/
划定你的正则表达式。所以https://
- >https:\/\/
。
`/\b((?:https: .. etc etc)/i`
尝试:
三,你的修饰语(?i)
尾随斜线后去(更改时间:逃脱/
,搬离(?i)regex
到/regex/i
正则表达式):
$pattern = '/\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)((?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))*)/i';
$textStr = preg_replace($pattern, "google.com", $textStr);
echo $textStr;
现在,由于$pattern
比赛整个网址,你只需要拿出:
"Test string contains google.com
google.com
google.com
google.com
google.com
more urls google.com some other text"
所以总之,我建议@安培的答案(但这比正常情况下有一个宽松的正则表达式),或者使用捕获括号和反向引用来做类似preg_replace($pattern,'google.com/\2',$textStr)
(但适当修改您的捕获括号,因为这样做不起作用与您当前的捕捉括号安排)。
This site对测试事情很有用。
正则表达式分隔符不一定是'/',它几乎可以是任何标点符号。例如,如果使用'〜',则不必转义任何东西,因为该字符从不出现在正则表达式中。另外,PHP支持'(?i)'(inline modifier)语法,所以你不需要改变它(但是结尾的修饰符也可以)。 – 2012-01-09 18:46:29
感谢您的澄清@AlanMoore,方便知道! – 2012-01-09 23:26:27
@ mathematical.coffee谢谢你的帮助。这正是我所期待的。 – James 2012-01-11 04:50:55
$patterrn='/([wW]{3,3}\.|)[A-Za-z0-9]+?\./';
$text="Test string contains http://foo.com/more_(than)_one_(parens)
http://foo.com/blah_(wikipedia)#cite-1
http://foo.com/blah_(wikipedia)_blah#cite-1
http://foo.com/unicode_(?)_in_parens
http://foo.com/(something)?after=parens
more urls foo.ca/me some other text";
$output = preg_replace($patterrn,"abc.",$text);
print_r($output);
输出将是代码,
Test string contains http://abc.com/more_(than)_one_(parens) http://abc.com/blah_(wikipedia)#cite-1 http://abc.com/blah_(wikipedia)_blah#cite-1 http://abc.com/unicode_(?)_in_parens http://abc.com/(something)?after=parens more urls abc.ca/me some other text
感谢您的帮助。虽然我无法将其用于当前的需求,但在其他情况下,这肯定会很方便。 – James 2012-01-11 04:56:29
[将ereg表达式转换为preg(缺少分隔符)](http://stackoverflow.com/questions/6270004/converting-ereg-expressions-to-preg) – mario 2012-01-09 05:56:26