Home  >  Article  >  Backend Development  >  How to get all links of content using php regular expression

How to get all links of content using php regular expression

WBOY
WBOYOriginal
2016-07-25 08:42:55862browse
The example in this article describes the method of obtaining all links of the content using php regular expressions. Share it with everyone for your reference. details as follows:

Here are two methods for php regular links. They can obtain all links of the content and save them to an array. Of course, they can also replace all links.

Method 1, the code is as follows:
  1. function get_all_url($code){
  2. preg_match_all('/"' ]+)["|' ]?s*[^>]*>([^>]+)/i',$code,$arr);
  3. return array('name'=>$arr[ 2],'url'=>$arr[1]);
  4. }
Copy code

Method 2, the code is as follows:
  1. $site=substr($url,0,strpos($url,"/",8));//Site
  2. $base=substr($url,0,strrpos ($url, "/")+1);//The directory where the file is located
  3. $fp = fopen($url, "r" );//Open the url
  4. while(!feof($fp))$ contents.=fread($fp,1024);//
  5. $pattern="|href=['"]?([^ '"]+)['" ]|u";
  6. preg_match_all($ pattern,$contents, $regarr, preg_set_order);//Match all href=
  7. for($i=0;$i
  8. if(!eregi ("://",$regarr[$i][1]))//Whether it is a relative path, that is, whether there is ://
  9. if(substr($regarr[$i][1],0, 1)=="/")//Is it the root directory of the site
  10. echo "link".($i+1).":".$site.$regarr[$i][1]."< br/>";//Root directory
  11. else
  12. echo "link".($i+1).":".$base.$regarr[$i][1]."
  13. else
  14. echo "link".($i+1).":".$regarr[$i][1]."
    ";//relative Path
  15. }
  16. fclose($fp);
Copy code

Regular expressions, php


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