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 zip code?
- How to use PHP regex to match a year?
- How to use PHP regex to match URL path?
- How to use PHP regex to match time?
- How to remove all non-numeric characters using PHP regex?
- How to remove non-printable characters using PHP regex?
- How to use PHP regex to match a line break?
- How to use PHP regex in a case insensitive mode?
- How to use PHP regex to match a hashtag?
- How to use PHP regex with zero or more occurrences?
See more codes...