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 to match a boolean value?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match an exact string?
- How to use PHP regex to match an XML tag?
- How to use PHP regex to match UUID?
- How to use PHP regex to match UTF8?
- How to match a double quote in PHP regex?
- How to use PHP regex to match URL path?
- How to use PHP regex to match URL?
- How to use PHP regex to match a hashtag?
See more codes...