簡體   English   中英

使用PHP從字符串中刪除包含其內部文本的鏈接的正則表達式

[英]Regular expression to remove links with their inner text from a string with PHP

我有以下代碼:

$string = 'Try to remove the link text from the content <a href="#">links in it</a> Try to remove the link text from the content <a href="#">testme</a> Try to remove the link text from the content';
$string = preg_replace('#(<a.*?>).*?(</a>)#', '$1$2', $string);
$result = preg_replace('/<a href="(.*?)">(.*?)<\/a>/', "\\2", $string);
echo $result; // this will output "I am a lot of text with links in it";

我正在尋找合並這些preg_replace行。 請提出建議。

您需要將DOM用於這些任務。 這是從您的內容中刪除鏈接的示例:

$str = 'Try to remove the link text from the content <a href="#">links in it</a> Try to remove the link text from the content <a href="#">testme</a> Try to remove the link text from the content';
$dom = new DOMDocument;
@$dom->loadHTML($str, LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD);
$xp = new DOMXPath($dom);
$links = $xp->query('//a');
foreach ($links as $link) {
    $link->parentNode->removeChild($link);
 }
echo preg_replace('/^<p>([^<>]*)<\/p>$/', '$1', @$dom->saveHTML());

由於文本節點是文檔中唯一的文本節點,因此PHP DOM創建了一個虛擬p節點來包裝文本,因此我正在使用preg_replace刪除它。 我認為這不是你的情況。

IDEONE演示

暫無
暫無

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

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