在php中我们经常会需要把字符串中的超级链接地址与url给过滤掉,下面我来利用php正则功能实现替换掉网页中所有超链接与url实例.
正则替换掉网页中所有超链接,代码如下:
- <?php
- $content = file_get_contents('test.html');
- $url = 'http://www.phpfensi.com'; //要换成的新网址
- $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.phpfensi.com';
- $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."</br>";
- }
|