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 the "s" modifier in 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 an XML tag?
- How to use regex in PHP to validate an email address?
- How to use PHP regex to match an exact string?
- How to use PHP regex to match time?
- How to remove a tag from a string using PHP regex?
- How to match a plus sign in PHP regex?
- How to use PHP regex to match URL path?
See more codes...