douzhen1234 2010-12-24 22:16
浏览 213
已采纳

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

this code get all img tags

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

but I want get tags that their filenames includes "next.gif" or "pre.gif"

for example :

$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">
';

and I output should be like this :

   <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条回答 默认 最新

  • dongyuling0312 2010-12-24 22:25
    关注

    I'd have to go with this one:

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

    Or in 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
    

    -- edit: Oops. I made a mistake. The . in pre.gif and next.gif in the regexp the regexp must be escaped!! I didn't before. -- edit

    PS. You might be using preg_match_all wrong. The arguments are: (pattern, subject, &matches)

    PS. The results of my pattern + your subject:

    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">
            )
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思