Php regular expression method for retrieving all links to content, php Regular Expression

Source: Internet
Author: User
Tags php regular expression

Php regular expression method for retrieving all links to content, php Regular Expression

This example describes how to obtain all links of the content using a php regular expression. Share it with you for your reference. The details are as follows:

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

Method 1: the code is as follows:
Copy codeThe code is as follows: function get_all_url ($ code ){
Preg_match_all ('/<as + href = ["|']? ([^> "'] +) [" |']? S * [^>] *> ([^>] +) </a>/I ', $ code, $ arr );
Return array ('name' => $ arr [2], 'url' => $ arr [1]);
}
Method 2: the code is as follows:
Copy codeCode: $ site = substr ($ url, 0, strpos ($ url, "/", 8); // site
$ Base = substr ($ url, 0, strrpos ($ url, "/") + 1); // directory of the file
$ 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 <count ($ regarr); $ I ++) {// traverse all matches
If (! Eregi (": //", $ regarr [$ I] [1]) // whether it is a relative path, that is, whether there are ://
If (substr ($ regarr [$ I] [1],) = "/") // whether it is 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]. "<br/>"; // Current Directory
Else
Echo "link". ($ I + 1). ":". $ regarr [$ I] [1]. "<br/>"; // relative path
}
Fclose ($ fp );

I hope this article will help you learn regular expressions.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.