Page 1 of 1

Regex errors

Posted: Tue Jan 13, 2009 4:14 am
by marcos.lavorato
Hi for all.

I am trying to find in a string for <img> HTML codes for extract. I waht to catch onde the src, in <img> tag. It's possible?

Excample of input

Code: Select all

Balalalal lalsldsf <img src="imgteste. jpg" align="left" height="99" width="130" alt="photo" title="eteste " border="0"/> dfgdfgdfgdfg

Code that's not working

Code: Select all

if(preg_match('@<img (.*?)/>@', $desc, $matches)){
echo ($matches[0]);
}
 
Something wrong?
Tanks.

Re: Regex errors

Posted: Tue Jan 13, 2009 6:16 am
by novice4eva
Humm i tried this, got the answer, but the whole <img ..> thing matches too!! Anyways check this

Code: Select all

preg_match('/<img(\s)+(?:.*)src="(.*)"/',$result,$matches);

Re: Regex errors

Posted: Wed Jan 14, 2009 5:01 am
by prometheuzz
Watch out with those greedy DOT-STAR operators!
A safer way would be to do:

Code: Select all

if(preg_match('@<img\s[^>]*src=[\'"]([^\'">]*)[\'"][^>]*>@'i, $desc, $matches)){
  echo "img -> " . $matches[0] . "<br />";
  echo "src -> " . $matches[1] . "<br />";
}
PS. note that the forum software removes the backslashes before the single quotes!