问题
有如下代码,要求不使用正则表达式的情况下修改链接为 https://www.2it.club/softs/
1 2 3 |
解决方法
笔者使用了DOMDocument进行操作,实例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php header( 'Content-Type: text/html; charset=utf-8' ); // 原始HTML代码 // 创建DOMDocument对象 $dom = new DOMDocument(); //$dom->encoding = 'UTF-8'; //@$dom->loadHTML($cont,LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); @ $dom ->loadHTML(mb_convert_encoding( $cont , 'HTML-ENTITIES' , 'UTF-8' ),LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); $aElem = $dom ->getElementsByTagName( 'a' ); // 给a链接添加rel="nofollow"属性 $aElem [0]->setAttribute( 'rel' , 'nofollow' ); $content = $dom ->saveHTML(); //$content = mb_convert_encoding($content, 'UTF-8', 'ISO-8859-1'); // 输出修改后的HTML代码 echo $content ; ?></p> |
运行上述代码,则页面源码即被修改为:
1 |
这里要注意:loadHTML载入html文本的时候,需要指定编码,笔者这里使用的是mb_convert_encoding($cont, 'HTML-ENTITIES','UTF-8')
进行编码转换,另外笔者所测试网上搜索到的$dom->encoding = 'UTF-8';
以及 $content = mb_convert_encoding($content, 'UTF-8', 'ISO-8859-1');
均未起到作用。
补充
此外,修改元素innerHtml属性也很简单,只需要设置其nodeValue值即可,上述示例继续扩展如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php header( 'Content-Type: text/html; charset=utf-8' ); //echo $codeid = date('YmdHis').mt_rand(1000,9999); // 原始HTML代码 // 创建DOMDocument对象 $dom = new DOMDocument(); //$dom->encoding = 'UTF-8'; //@$dom->loadHTML($cont,LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); @ $dom ->loadHTML(mb_convert_encoding( $cont , 'HTML-ENTITIES' , 'UTF-8' ),LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); $aElem = $dom ->getElementsByTagName( 'a' ); // 给a链接添加rel="nofollow"属性 $aElem [0]->setAttribute( 'rel' , 'nofollow' ); //修改span元素的innerHtml值 $spanElem = $dom ->getElementsByTagName( 'span' ); $spanElem [0]->nodeValue = '【IT俱乐部软件下载】===>' ; $content = $dom ->saveHTML(); //$content = mb_convert_encoding($content, 'UTF-8', 'ISO-8859-1'); // 输出修改后的HTML代码 echo $content ; ?></p> |
此时再次访问,页面元素就变成了:
1 | < p >欢迎访问< span >【IT俱乐部软件下载】===></ span >< a href = "https://www.2it.club/softs/" rel = "nofollow" >软件下载</ a ></ p > |