Home > php教程 > PHP源码 > php 正则替换掉网页中所有超链接 过滤网页中所有Url

php 正则替换掉网页中所有超链接 过滤网页中所有Url

WBOY
Release: 2016-06-08 17:23:37
Original
1723 people have browsed it

在php中我们经常会需要把字符串中的超级链接地址与url给过滤掉,下面我来利用php正则功能实现替换掉网页中所有超链接与url实例,各位朋友可参考。

<script>ec(2);</script>

正则替换掉网页中所有超链接

 代码如下 复制代码

$content = file_get_contents('test.html');
$url = 'http://www.111cn.net';  //要换成的新网址
$preg = '/[s]href=("|')[S]*("|')/i';
$replace = ' href="' . $url . '"';
$content = preg_replace($preg, $replace, $content);  //正则替换
create_log('newhtml', $content);  //生成新文件
?>

下面是写文件操作

 代码如下 复制代码

function create_log($filename, $text) {
       if ( strtolower(substr($filename, -4)) != 'html' ){
              $filename .= '.html';
       }
       $filename = dirname ( __FILE__ ) . '/' . $filename;
       if (!file_exists ( $filename )) {
              exec( 'touch '. $filename);
              exec( 'chmod 777 '. $filename);
       }
       $handle = fopen ( $filename, "w+b" );
       $text .= "rn";
       fwrite($handle, $text);
       fclose ( $handle );
}

下面我一个采集的功能

 代码如下 复制代码

$url ='http://www.111cn.net';
$body=@file_get_contents($url);
preg_match_all('/href=['"]?([^'"]*)['"]?>(.*)/i',$body,$b);
$nums = array();
foreach($b[1] as $u){
  if(in_array($u,$nums)){
  continue;
  }
  $nums[]=$u;
  $title=strip_tags($u);
  echo $title."";
}

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template