开发者

PHP regular expression for getting image source from anchor tag

I need help to get the image source from image tab which is comprised into an anchor tag, e.g.

<p>this is sample text <a href="a link to some site"><img src="imagesource" height='x' width='y' /></a><p>

from above text string I want to retrieve the image source.

here is the actual description from which I have to extract the source for first image tag only

$desc = "<p></p><p><a href='http://somesitename.com/wp-content/uploads/2007/08/100_2666.JPG' title='100_2666.JPG'><img width=\"400\" src='http://somesitename.com/wp-content/uploads/2007/08/100_2666.JPG' alt='100_2666.JPG' /></a></p><p><a href='http://somesitename.com/wp-content/uploads/2007/08/100_2667.JPG' title='100_2667.JPG'><img width=\"400\" src='http://somesitename.com/wp-content/uploads/2007/08/100_2667.JPG' alt='100_2667.JPG' /></a></p><p>These are some of the variations of cotton floral prints used by the Knickerbocker Toy Co. in the 1960's. I constantly search for more examples of the unusual early prints an开发者_运维百科d sometimes have to purchase a doll in fair condition just to have her dress!! See the article about the Knickerbocker Anns that follows.</p>";

$imgsrc_regex = '/<a (.*)><img.+?src=(\'|")(.+?)(\'|")[^>]*><(.*\/)*a>/';
preg_match($imgsrc_regex, $desc, $arr_match_array);

The above arr_match_array returns all anchor image tags where as I want to get only the first


$x = <<<_A_
<p>this is sample text <a href="a link to some site"><img src="imagesource" height='x' width='y' /></a></p>
_A_;
$s = simplexml_load_string($x);
$images = $s->xpath('//img');
echo $images[0]['src'];


/<\s*?img\s+[^>]*?\s*src\s*=\s*(["'])[[\\?+.]*?]\1[^>]*?>/

Although I would suggest you don't use regex, since HTML code may not be 100% compliant. Try using an HTML parser like:

http://people.virginia.edu/~rtg2t/rda/ref.manual.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜