使用正则表达式从HTML获取图像src

I have HTML like

<td class="td_scheda_modello_dati">

       <img src="/webapp/safilo/gen_img/p_verde.gif" width="15" height="15" alt="" border="0">

</td>

I want to extract the img src from this HTML using preg_match_all().

I have done this

preg_match_all('#<td class=td_scheda_modello_dati>(.*)<td>#',$detail,$detailsav);

It should give the whole img tag.But it doesn't give me the img tag. So what changes should be done to get the specific value?

Long story short: ideone

You should not use Regex, but instead an HTML parser. Here's how.

<?php
$html = '<img src="/webapp/safilo/gen_img/p_verde.gif" width="15" height="15" alt="" border="0">';
$xpath = new DOMXPath(@DOMDocument::loadHTML($html));
$src = $xpath->evaluate("string(//img/@src)");
echo $src;
?>

Try this code.

$html_text =  '<td class="td_scheda_modello_dati">   
            <img src="/webapp/safilo/gen_img/p_verde.gif" width="15" height="15" alt=""    border="0"></td>';

preg_match( '/src="([^"]*)"/i', $html_text , $res_array ) ;

print_r($res_array);

Try this: <img[^>]*src="([^"]*/gen_img/p_verde.gif)"

Try using the s modifier after your regex. The default behavior for the dot character is not to match newlines (which your example has).

Something like:

preg_match_all('#<td class=td_scheda_modello_dati>(.*)</td>#s',$detail,$detailsav);

Should do the trick.

It's worth reading up a bit on modifiers, the more you do with regex the more useful they become.

http://php.net/manual/en/reference.pcre.pattern.modifiers.php

Edit: also, just realized that the code posted was missing a closing td tag (it was <td> instead of </td>). Fixed my example to reflect that.