如何获得第一个图像的字符串使用PHP?
问题描述:
我用这个代码:如何获得第一个图像的字符串使用PHP?
<?php
$texthtml = '<p>test</p><br><p><img src="1.jpeg" alt=""><br></p><p><img src="2.png" alt=""><br><img src="3.png" alt=""></p>';
preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $texthtml, $image);
echo $image['src'];
?>
然而,当我测试了一下,我得到最后的图像(3.png)
从一个字符串。
我想知道如何才能在字符串中获得第一张图像(1.jpeg)
。
答
尝试:
preg_match('/<img(?: [^<>]*?)?src=([\'"])(.*?)\1/', $texthtml, $image);
echo isset($image[1]) ? $image[1] : 'default.png';
答
正则表达式是不适合的HTML标签。
你可以在这里阅读:RegEx match open tags except XHTML self-contained tags
我建议DOM文件,如果它比你在这里显示的更复杂。
如果它不比这更复杂,我建议strpos找到单词并用substr“修剪”它。
$texthtml = '<p>test</p><br><p><img src="1.jpeg" alt=""><br></p><p><img src="2.png" alt=""><br><img src="3.png" alt=""></p>';
$search = 'img src="';
$pos = strpos($texthtml, $search)+ strlen($search); // find postition of img src" and add lenght of img src"
$lenght= strpos($texthtml, '"', $pos)-$pos; // find ending " and subtract $pos to find image lenght.
echo substr($texthtml, $pos, $lenght); // 1.jpeg