2017-08-06 76 views
0

我用這個代碼:如何獲得第一個圖像的字符串使用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)

回答

0

嘗試:

preg_match('/<img(?: [^<>]*?)?src=([\'"])(.*?)\1/', $texthtml, $image); 
echo isset($image[1]) ? $image[1] : 'default.png'; 
0

正則表達式是不適合的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 

https://3v4l.org/48iiI

相關問題