PHP:删除文本特定域的所有超链接(PHP: Remove all hyperlinks of sp

2019-10-30 05:23发布

两件事情:

  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 '; 

Answer 1:

这应该做的伎俩在2个步骤:

<?

$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>部分。



文章来源: PHP: Remove all hyperlinks of specific domain from text