You need to enable JavaScript to run this app. 在Laravel 7.x控制器中如何提取字符串内的图片URL地址
优惠活动
大模型
产品
解决方案
定价
更多

在Laravel 7.x控制器中如何提取字符串内的图片URL地址

Laravel 7.x 提取HTML字符串中img标签src属性解决方案

两种可直接在控制器中使用的实现方式如下:

方案1:使用PHP内置DOMDocument解析(推荐)

该方案稳定性更高,即使HTML结构不标准、属性顺序变化也能准确提取,不会出现正则漏匹配的问题。
代码示例:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ImageExtractController extends Controller
{
    public function getImgSrc()
    {
        // 实际业务中此处替换为你的带HTML标签的业务字符串
        $value = "<p>this is a test</p><div class='myClass'>this is a test</div><img src='http://www.google.com/1.jpg'>";
        
        // 临时抑制非标准HTML解析警告
        libxml_use_internal_errors(true);
        $dom = new \DOMDocument();
        $dom->loadHTML($value);
        libxml_clear_errors();

        $srcList = [];
        foreach ($dom->getElementsByTagName('img') as $img) {
            if ($img->hasAttribute('src')) {
                $srcList[] = $img->getAttribute('src');
            }
        }

        // 仅需单张图片地址直接取第一个元素即可
        $targetSrc = $srcList[0] ?? '';
        
        dd($targetSrc); // 输出结果:http://www.google.com/1.jpg
    }
}

方案2:正则匹配(适合简单场景)

如果你的HTML结构固定、格式标准,可以用正则快速实现,写法更简洁:

preg_match('/<img[^>]+src\s*=\s*["\']?([^"\'>]+)["\']?[^>]*>/i', $value, $matches);
$targetSrc = $matches[1] ?? '';

内容的提问来源于stack exchange,提问作者peyman beiati

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 10:06:02