PHP:从文本中删除特定域名的所有超链接

2022-03-23 00:00:00 php preg-replace preg-match

2件事:

  1. 删除指向mydomain.com的所有超链接&&;保留不属于此域的所有其他超链接。

  2. 对于其余所有其他URL,抓取标记之间的值并将其显示为ID。

1.关于第一个任务:

我有这个:

$str = 'I have been searching <a href="http://www.google.com">Google</a> for all the valuable information. I have also tried <a href="http://www.yahoo.com">Yahoo</a> and I finally, ended up finding it at
<font size="1">My Site <a style="color:#0000ff;font-family:Arial,Helvetica,sans-serif" href="http://www.mydomain.com/go.php?offer=fine&amp;pid=10" target="_blank" >My Link</a></font>. So you can visit <a href="http://www.mydomain.com/go.php?offer=ok" target="_blank">My Link</a>'; 

我想要这个:

$str = 'I have been searching <a href="http://www.google.com">Google</a> for all the valuable information. I have also tried <a href="http://www.yahoo.com">Yahoo</a> and I finally, ended up finding it at . So you can visit '; 

我尝试的内容:

我尝试了下面的preg_place,但它删除了所有链接。我只想让它删除mydomain.com上的所有链接,并保留其他所有内容。

$pattern = "/<a[^>]*>(.*)</a>/iU";
$final_str = preg_replace($pattern, "$1", $str);

2.关于第二个任务:

最后,我想以以下内容结束:

$str = 'I have been searching <a href="http://www.google.com" id="Google">Google</a> for all the valuable information. I have also tried <a href="http://www.yahoo.com" id="Yahoo">Yahoo</a> and I finally, ended up finding it at . So you can visit '; 

解决方案

此操作应分两步完成:

<?

$str = 'I have been searching <a href="http://www.google.com">Google</a> for all the valuable information. I have also tried <a href="http://www.yahoo.com">Yahoo</a> and I finally, ended up finding it at <font size="1">My Site <a style="color:#0000ff;font-family:Arial,Helvetica,sans-serif" href="http://www.mydomain.com/go.php?offer=fine&amp;pid=10" target="_blank" >My Link</a></font>. So you can visit <a href="http://www.mydomain.com/go.php?offer=ok" target="_blank">My Link</a>';

// removing the domain links
$pattern1 = '|<a [^>]*href="http://www.mydomain.com[^"]*"[^>]*>.*</a>|iU';
$str = preg_replace($pattern1, '', $str);

// adding IDs
$pattern2 = '|(<a [^>]+)>(.*)</a>|iU';
$str = preg_replace($pattern2, '$1 id="$2">$2</a>', $str);

如果您还需要删除<font size="1">My Site </font>部分,请让我知道。

相关文章