[英]php regex match only none http://, https://
我有關於如何只匹配無http://,https://
。
這是我的正則表達式,現在它選擇所有鏈接並替換為我的完整網址。
但問題是當我的$string
得到正確的 url 但替換函數總是用http://example.comhttp://google.com/test
替換它
$string = 'test <a href="/web/data.html">link1</a> <a href="http://google.com/test">link2</a>';
$pattern = "/<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>/siU";
$response = preg_replace_callback($pattern, function ($matches) {
return '<a href="http://example.com'.$matches[2].'">'.$matches[3].'</a>';
}, $string);
var_dump($response);
現在的結果是:
test <a href="http://example.com/web/data.html">link1</a> <a href="http://example.comhttp://google.com/test">link2</a>
預期結果是:
test <a href="http://example.com/web/data.html">link1</a> <a href="http://google.com/test">link2</a>
謝謝。
您可以使用更簡單的方法與這樣的正則表達式:
href="/
和替換字符串:
href="http://example.com/
php代碼
$re = '~href="/~';
$str = "test <a href=\"/web/data.html\">link1</a> <a href=\"http://google.com/test\">link2</a>\n\n";
$subst = "href=\"http://example.com/";
$result = preg_replace($re, $subst, $str);
// output
test <a href="http://example.com/web/data.html">link1</a> <a href="http://google.com/test">link2</a>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.