簡體   English   中英

PHP 使用正則表達式從 html 字符串中獲取圖像 url

[英]PHP get image url from html-string using regular expression

我正在嘗試使用 php 從 html 字符串中獲取所有圖像 url。 來自 img-tags 和內聯 css (背景圖像)

<?php
$html = '
<div style="background-image : url(https://exampel.com/media/logo.svg);"></div>
<img src="https://exampel.com/media/my-photo.jpg" />
<div style="background-image:url('https://exampel.com/media/icon.png');"></div>
';


preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>|background-image[ ]?:[ ]?url\([ ]?[\']?["]?(.*?\.(?:png|jpg|jpeg|gif|svg))/i', $html, $image);
echo('<pre>'.print_r($image, true).'</pre>');
?>

output 是:

Array
(
    [0] => background-image : url(https://exampel.com/media/logo.svg
    [src] => 
    [1] => 
    [2] => https://exampel.com/media/logo.svg
)

首選 output 將是:

Array
(
    [0] => https://exampel.com/media/logo.svg
    [1] => https://exampel.com/media/my-photo.jpg
    [2] => https://exampel.com/media/icon.png
)

我在這里遺漏了一些東西,但我不知道是什么

使用 preg_match_all() 並重新排列您的結果:

<?php
$html = <<<EOT
<div style="background-image : url(https://exampel.com/media/logo.svg);"></div>
<img src="https://exampel.com/media/my-photo.jpg" />
<div style="background-image:url('https://exampel.com/media/icon.png');"></div>
EOT;

preg_match_all(
    '/<img.+src=[\'"](.+?)[\'"].*>|background-image ?: ?url\([\'" ]?(.*?\.(?:png|jpg|jpeg|gif|svg))/i',
    $html,
    $matches,
    PREG_SET_ORDER
);

$image = [];
foreach ($matches as $set) {
    unset($set[0]);
    foreach ($set as $url) {
        if ($url) {
            $image[] = $url;
        }
    }
}

echo '<pre>' . print_r($image, true) . '</pre>' . PHP_EOL;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM