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:
- function get_all_url($code){
-
- preg_match_all('/"' ]+)["|' ]?s*[^>]*>([^>]+)/i',$code,$arr);
-
- return array('name'=>$arr[ 2],'url'=>$arr[1]);
-
- }
Copy code
Method 2, the code is as follows:
- $site=substr($url,0,strpos($url,"/",8));//Site
-
- $base=substr($url,0,strrpos ($url, "/")+1);//The directory where the file is located
-
- $fp = fopen($url, "r" );//Open the url
-
-
-
- while(!feof($fp))$ contents.=fread($fp,1024);//
-
- $pattern="|href=['"]?([^ '"]+)['" ]|u";
-
-
-
- preg_match_all($ pattern,$contents, $regarr, preg_set_order);//Match all href=
-
- for($i=0;$i
- if(!eregi ("://",$regarr[$i][1]))//Whether it is a relative path, that is, whether there is ://
- if(substr($regarr[$i][1],0, 1)=="/")//Is it the root directory of the site
- echo "link".($i+1).":".$site.$regarr[$i][1]."< br/>";//Root directory
-
- else
-
- echo "link".($i+1).":".$base.$regarr[$i][1]."
- else
- echo "link".($i+1).":".$regarr[$i][1]."
";//relative Path
-
- }
-
- fclose($fp);
Copy code
|