[英]Error escaping quotes in regular expressions in PHP
我是PHP的新手,並嘗試在下面的代碼中使用google.com替換URL模式。
$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()未知修飾符'\\'但是我使用斜杠()來轉義{};中的單引號:\\'“
有人可以幫我解決上面的代碼嗎?
$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
在preg_replace
的第一個位置,您必須用/
分隔正則表達式,如:
/\b((?:https: ... etc etc)/
其次,因為你使用/
來分隔你的正則表達式,你必須使用反斜杠轉義任何/
。 所以https://
- > https:\\/\\/
。
第三,你的修飾符(?i)
追蹤尾隨斜杠:
`/\b((?:https: .. etc etc)/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
匹配整個URL,你只需要:
"Test string contains google.com
google.com
google.com
google.com
google.com
more urls google.com some other text"
所以總的來說,我建議使用@Ampere的答案(但這比你的原始版本有更寬松的正則表達式),或者使用捕獲括號和反向引用來做preg_replace($pattern,'google.com/\\2',$textStr)
(但要適當修改捕捉支架,因為這不適用於您當前的捕捉支架布置)。
該站點對於測試內容非常有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.