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


PHP: Remove all hyperlinks of specific domain from text

两件事:

  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_replace,但它删除了所有链接。我只想让它删除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>部分,请告诉我。