Home >Backend Development >PHP Tutorial >【紧急求救】正则或类、PHP替换非本站域名

【紧急求救】正则或类、PHP替换非本站域名

WBOY
WBOYOriginal
2016-06-23 13:58:50996browse

一个论坛程序,将用户帖子中的链接(*非本站的域名下的链接)全部替换成指定连接


例如源 代码:


-------------------------------------------------

<a href="http://www.AAA.com/" target="_blank">AAAAA</a><a href="http://wer.123.com/" target="_blank">BBBBB</a><a href="http://adf.h4.456.com/" target="_blank">CCCCC</a><a href="http://wer.AAA.com/" target="_blank">DDDDD</a><a href="http://asdgwre.wer.222.789.com/" target="_blank">EEEEE</a><a href="http://fadsf.543.com/" target="_blank">FFFFF</a><a href="http://234r.231.com/" target="_blank">GGGGG</a>


-----------------------------------------------------------
替换成

-----------------------------

<a href="http://www.AAA.com/" target="_blank">AAAAA</a><a href="#" target="_blank">BBBBB</a><a href="#" target="_blank">CCCCC</a><a href="http://wer.AAA.com/" target="_blank">DDDDD</a><a href="#" target="_blank">EEEEE</a><a href="#" target="_blank">FFFFF</a><a href="#" target="_blank">GGGGG</a>


------------------------


需求:将非AAA.com域名下的链接全部替换成“#”井号

以下代码可以替换所有链接为井号,但是不能分辨是否为AAA.COM
echo preg_replace("/(?]*)(?=\>)/i","javascript:;", "你好,点这里看看你好,点这里看看"); 

求正则大神帮忙哈  很着急 一上午没弄出来


回复讨论(解决方案)

$str = <<<str<a href="http://www.AAA.com/" target="_blank">AAAAA</a><a href="http://wer.123.com/" target="_blank">BBBBB</a><a href="http://adf.h4.456.com/" target="_blank">CCCCC</a><a href="http://www.wer.AAA.com/" target="_blank">DDDDD</a><a href="http://asdgwre.wer.222.789.com/" target="_blank">EEEEE</a><a href="http://fadsf.543.com/" target="_blank">FFFFF</a><a href="http://234r.231.com/" target="_blank">GGGGG</a>str;echo preg_replace_callback("/http\:\/\/[^.]*[^A]+\.com\//is",function($r) { return str_replace($r[0], "#", $r[0]); },$str);

替换成这样滴  谢谢哈

<a href="http://www.AAA.com/" target="_blank">AAAAA</a>BBBBCCCCC<a href="http://wer.AAA.com/" target="_blank">DDDDD</a>EEEEEFFFFFGGGGG

echo preg_replace_callback("/<a href=\"http\:\/\/[^.]*[^A]+\.com\/\" target=\"_blank\">([^<]+)<\/a>/is",function($r) { return strip_tags($r[0]); },$str);

感谢microlab2009   
但是在应用中我测试了一下发现几个问题


1:将非本站链接替换成井号,但是非链接也给替换了哦!
例如:和www.163.com(字符串非链接)全部都给替换成#井号了

2:删除链接
BBBBB

BBBBB
处理上出现错误,能修改第一个不能修改第二个。

望大神帮帮忙哈,无限的感谢已涌向心口........

1. $str =  AAAAA
BBBBB
CCCCC
DDDDD
EEEEE
FFFFF
GGGGG
http://234r.231.com
str;

echo preg_replace_callback("/ (? ?>

2.echo preg_replace_callback("/]*>([^/is",function($r) { return strip_tags($r[0]); },$str);
都只是改改正则就可以了 还是得自己去先把正则熟悉熟悉

感谢大神的帮助 万分感谢哈~~~


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn