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">
此代码获取所有img标签 p>
preg_match_all('/ &lt; img [^&gt;] +&gt; / i',$ a,$ page);
code> pre>
但我想要获取其文件名包含的标签“next .gif“或”pre.gif“ p>
例如: p>
$ page ='
&lt; img border =”0“ alt =“icon”src =“http://www.site.com/images/man.gif”width =“90”height =“90”&gt;
&lt; img border =“0”alt =“icon” src =“http://www.site.com/images/pre.gif”width =“90”height =“v”&gt;
&lt; 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”&gt;
';
code> pre>
我的输出应该是这样的: p>
&lt; img border =“0”alt =“icon”src =“http://www.site.com/images/pre.gif”width =“90”height =“90”&gt;
&lt; img border =“0”alt =“icon”src =“http://www.site.com/images/next.gif”width =“90”height =“90”&gt;
code> pre>
div>
答
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"> ) )