preg_match_all,获取包含字符串的所有img标记

时间:2010-12-24 22:16:39

标签: php regex preg-match-all

此代码获取所有img标记

preg_match_all('/<img[^>]+>/i',$a,$page);

但我希望获取标签,其文件名包含“next.gif”或“pre.gif”

例如:

$page = '
<img border="0" alt="icon" src="http://www.site.com/images/man.gif" width="90" height="90">
<img border="0" alt="icon" src="http://www.site.com/images/pre.gif" width="90" height="v">
<img border="0" alt="icon" src="http://www.site.com/images/2.gif">
<img border="0" alt="icon" src="http://www.site.com/images/next.gif" width="90" height="90">
';

我的输出应该是这样的:

   <img border="0" alt="icon" src="http://www.site.com/images/pre.gif" width="90" height="90">
    <img border="0" alt="icon" src="http://www.site.com/images/next.gif" width="90" height="90">

1 个答案:

答案 0 :(得分:1)

我必须选择这个:

/(<img[^>]*src=".*?(?:pre\.gif|next\.gif)"[^>]*>)/i

或者在PHP中:

$regexp = '/(<img[^>]*src=".*?(?:pre\.gif|next\.gif)"[^>]*>)/i';
$iResults = preg_match_all($regexp, $str, $aMatches);
print_r($aMatches); // you'll see what you need

- 编辑: 哎呀。我犯了一个错误。正则表达式中.pre.gif中的next.gif必须转义正则表达式!!我之前没有。 - 编辑

PS。您可能使用preg_match_all错误。参数是:(patternsubject&matches

PS。我的模式+你的主题的结果:

Array
(
    [0] => Array
        (
            [0] => <img border="0" alt="icon" src="http://www.site.com/images/pre.gif" width="90" height="v">
            [1] => <img border="0" alt="icon" src="http://www.site.com/images/next.gif" width="90" height="90">
        )
    [1] => Array
        (
            [0] => <img border="0" alt="icon" src="http://www.site.com/images/pre.gif" width="90" height="v">
            [1] => <img border="0" alt="icon" src="http://www.site.com/images/next.gif" width="90" height="90">
        )
)