preg_match() matching quotes – How to escape quotes

I was having the most difficult time getting preg_match() to match a double quote.

$string = '<a href="https://www.calcmaster.net/" class="link">calcmaster.NET</a>';
if ( preg_match('/src="(.+?)"/', $string, $matches) ) {
$url = $matches[1];
}

This did not work for me.  I assumed that the source string may have had some unicode characters for the double quotes so I converted the string to ISO-8859-1 like this:

$string = iconv("utf-8","ISO-8859-1//TRANSLIT",$string);

I still couldn’t get it to work.  In my string there was apparently another character between the src= and the double quote that I could not see.  The following code matches any characters that might be between the src= and the double quote if there are any:

$string = '<a href="https://www.calcmaster.net/">calcmaster.NET</a>';
if ( preg_match('/src=.*?"([^"]+)/', $string, $matches) ) {
$url = $matches[1];
}

That code will match any character or no characters between the src= and the quote and then will match the url by only matching characters which are not a quote.  If preg_match() is not working to match quotes then try something like the above. Happy matching!


Posted

in

by

Tags: