php-regexHow to use PHP regex to match URL path?
Using PHP regex to match URL path is a powerful way to validate and parse URLs. The following example code block shows how to use regex to match a URL path:
$url = 'http://www.example.com/path/to/page';
if (preg_match('#^https?://www\.example\.com/([^/]+)#i', $url, $matches)) {
echo 'Path is: ' . $matches[1];
}
The output of the example code is:
Path is: path/to/page
Code explanation
-
$url = 'http://www.example.com/path/to/page';
: This line assigns the URL to a variable. -
if (preg_match('#^https?://www\.example\.com/([^/]+)#i', $url, $matches)) {
: This line uses thepreg_match
function to match the URL path. The#^https?://www\.example\.com/([^/]+)#i
part is the regex pattern used to match the URL path. -
echo 'Path is: ' . $matches[1];
: This line prints out the URL path. The$matches[1]
part is used to access the first matched group in the regex pattern.
Helpful links
More of Php Regex
- How to match a space using PHP regex?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match a zip code?
- How to use an "or" condition in PHP regex?
- How to use PHP regex to get a YouTube video ID?
- How to convert a PHP regex to JavaScript regex?
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to match a year?
- How to use PHP regex with the "x" modifier?
- How to use PHP regex to match special characters?
See more codes...