Home  >  Article  >  Backend Development  >  A simple way to match URLs with regular expressions in php_PHP Tutorial

A simple way to match URLs with regular expressions in php_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:25:201090browse

An alternative to the parse_url() function seen on PHP’s official website. The result is similar to the parse_url() function, which is implemented using regular expressions. A URI is that every resource available on the Web - HTML documents, images, video clips, programs, etc. - is located by a Universal Resource Identifier ("URI"). Object grouping:

Copy code The code is as follows:

^(([^:/?#]+):)? (//([^/?#]*))?([^?#]*)(?([^#]*))?(#(.*))?
12 3 4 4

The test code is as follows:
Copy codeThe code is as follows:

$ search = '~^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(?([^#]*) )?(#(.*))?~i';
$url = 'http://www.jb51.net/pub/ietf/uri/#Gonn';
$url = trim($ url);
preg_match_all($search, $url ,$rr);
printf("

The output URL data is:

%s
n" ,var_export( $rr ,TRUE));

/*
Each group is as follows
$1 = http:
$2 = http
$3 = //www.nowamagic.net
$4 = www.nowamagic.net
$5 = /pub/ietf/uri/
$6 =
$7 =
$8 = #Gonn
$9 = Gonn
*/
?>


The above regular expression can get any part of the URL, the following code is simpler:
Copy code Code As follows:

// Get the host name from the URL
preg_match("/^(http://)?([^/]+)/i ", "http://www.jb51.net/index.html", $matches);
$host = $matches[2];
// Get the next two paragraphs from the host name
preg_match("/[^./]+.[^./]+$/", $host, $matches);
echo "domain name is: {$matches[0]}n";
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/825116.htmlTechArticleAn alternative to the parse_url() function seen on PHP’s official website. The result is similar to the parse_url() function, which is implemented using regular expressions. A URI is for every resource available on the web - HTML documents, images...
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