php-regexHow to use PHP regex to match a URL in a href attribute?
To match a URL in a href attribute using PHP regex, you can use the following code:
$pattern = '/href="(.*?)"/';
$string = '<a href="http://example.com">Link</a>';
preg_match($pattern, $string, $matches);
The output of the code will be:
Array
(
[0] => href="http://example.com"
[1] => http://example.com
)
Code explanation
$pattern
: This is the regular expression used to match the URL in the href attribute.$string
: This is the string containing the HTML element with the href attribute.preg_match()
: This is the PHP function used to match the regular expression against the string.
Helpful links
More of Php Regex
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to get a YouTube video ID?
- How to use named capture groups in PHP regex?
- How to use PHP regex to match an exact string?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to get the first match when using regex in PHP?
- How to use PHP regex with the "x" modifier?
- How to use PHP regex to match a zip code?
- How to match a single quote in PHP regex?
- How to use PHP regex to match special characters?
See more codes...