簡體   English   中英

PHP preg_replace:用正則表達式將文本中的所有錨標記替換為它們的 href 值

[英]PHP preg_replace: Replace all anchor tags in text with their href value with Regex

我想用它們的 href 值替換文本中的所有錨標記,但我的模式不能正常工作。

$str = 'This is a text with multiple anchor tags. This is the first one: <a href="https://www.link1.com/" title="Link 1">Link 1</a> and this one the second: <a href="https://www.link2.com/" title="Link 2">Link 2</a> after that a lot of other text. And here the 3rd one: <a href="https://www.link3.com/" title="Link 3">Link 3</a> Some other text.';
$test = preg_replace("/<a\s.+href=['|\"]([^\"\']*)['|\"].*>[^<]*<\/a>/i",'\1', $str);
echo $test;

最后,文本應如下所示:

This is a text with multiple anchor tags. This is the first one: https://www.link1.com/ and this one the second: https://www.link2.com/ after that a lot of other text. And here the 3rd one: https://www.link3.com/ Some other text.

非常感謝你!

只是不要。

改用解析器。

$dom = new DOMDocument();
// since you have a fragment, wrap it in a <body>
$dom->loadHTML("<body>".$str."</body>");
$links = $dom->getElementsByTagName("a");
while($link = $links[0]) {
    $link->parentNode->insertBefore(new DOMText($link->getAttribute("href")),$link);
    $link->parentNode->removeChild($link);
}
$result = $dom->saveHTML($dom->getElementsByTagName("body")[0]);
// remove <body>..</body> wrapper
$output = substr($result, strlen("<body>"), -strlen("</body>"));

3v4l 演示

也許不是更簡單,但更安全的是用 strpos 循環字符串以查找和剪切字符串並刪除 html。

$str = 'This is a text with multiple anchor tags. This is the first one: <a class="funky-style" href="https://www.link1.com/" title="Link 1">Link 1</a> and this one the second: <a href="https://www.link2.com/" title="Link 2">Link 2</a> after that a lot of other text. And here the 3rd one: <a href="https://www.link3.com/" title="Link 3">Link 3</a> Some other text.';

$pos = strpos($str, '<a');

while($pos !== false){
    // Find start of html and remove up to link (<a href=")
    $str = substr($str, 0, $pos) . substr($str, strpos($str, 'href="', $pos)+6);
    // Find end of link and remove that.(" title="Link 1">Link 1</a>)
    $str = substr($str, 0, strpos($str,'"', $pos)) . substr($str, strpos($str, '</a>', $pos)+4);
    // Find next link if possible
    $pos = strpos($str, '<a');
}
echo $str;

https://3v4l.org/vdN7E

編輯以處理 a 標簽的不同順序。

如果您仍然使用正則表達式,這應該有效:

preg_replace("/<a\s+href=['\"]([^'\"]+)['\"][^\>]*>[^<]+<\/a>/i",'$1', $str);

但是使用 Andreas 發布的解決方案可能會更好。

僅供參考:您之前的正則表達式不起作用的原因是這個小數字:

.*>

因為. 選擇您最終匹配要替換的 url 之后的所有內容; 一直到最后。 這就是為什么它似乎只選擇並替換它找到的第一個錨標簽並切斷其余的。

將其更改為

[^\>]*

確保此特定選擇僅限於存在於 url 和 a 標記的結束括號之間的字符串部分。

如果你想用 href 值替換標簽,你可以這樣做:

$post = preg_replace("/<a.*?href=\"(.*?)\".*?>(.*?)<\/a>/","$1",$post);

如果要替換為文本值:

$post = preg_replace("/<a.*?href=\"(.*?)\".*?>(.*?)<\/a>/","$2",$post);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM