Skip to content
Advertisement

Extract link attributes from string of HTML

What’s the best way to extract HTML out of $var?

example of $var

$var = "<a href="http://stackoverflow.com/">Stack Overflow</a>"

I want

$var2 = "http://stackoverflow.com/"

example: preg_match();

what else?

Advertisement

Answer

Instead of crafting long complicated regex, do it in steps

$str = '<a href="http://stackoverflow.com/"> Stack Overflow</a>';
$str = preg_replace("/.*<as+href="/","",$str);
print preg_replace("/">.*/","",$str);

one way of “non regex”, using explode

$str = '<a href="http://stackoverflow.com/"> Stack Overflow</a>';
$s = explode('href="',$str);
$t = explode('">',$s[1]);
print $t[0];
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement