php - 正则表达式查找 img 标签内的图像名称
问题描述
今天,表达式验证如果空图像的 ALT 标记为空,则用 Replace 变量中的内容填充。
但基本上我想要的是在替换变量中放置图像的名称,输出中看到的图像名称在此模式中。
http://dominio.com.br/wp-content/uploads/2020/09/amazon-prime-channels.jpg
由于 url、日期和文件名和扩展名不同
<?php
$content = 'Conteudo alt=""<img loading="lazy" class="aligncenter wp-image-71444 size-medium lazyloaded" src="http://idinheiro.local/wp-content/uploads/2020/09/amazon-prime-channels-300x225.jpg" alt="" width="300" height="225" sizes="(max-width: 300px) 100vw, 300px" srcset="http://idinheiro.local/wp-content/uploads/2020/09/amazon-prime-channels-300x225.jpg 300w, http://idinheiro.local/wp-content/uploads/2020/09/amazon-prime-channels-768x576.jpg 768w, http://idinheiro.local/wp-content/uploads/2020/09/amazon-prime-channels-554x416.jpg 554w, http://idinheiro.local/wp-content/uploads/2020/09/amazon-prime-channels.jpg 960w" data-ll-status="loaded">';
$pattern = '~(<img.*? alt=")("[^>]*>)~i';
$replace = '$1Here should be the name of the image$2';
$content = preg_replace( $pattern, $replace, $content );
echo $content;
?>
解决方案
您可以使用此正则表达式来获取src
属性值。这演示了如何:
<?php
// Your content.
$content = 'Conteudo alt=""<img loading="lazy" class="aligncenter wp-image-71444 size-medium lazyloaded" src="http://idinheiro.local/wp-content/uploads/2020/09/amazon-prime-channels-300x225.jpg" alt="" width="300" height="225" sizes="(max-width: 300px) 100vw, 300px" srcset="http://idinheiro.local/wp-content/uploads/2020/09/amazon-prime-channels-300x225.jpg 300w, http://idinheiro.local/wp-content/uploads/2020/09/amazon-prime-channels-768x576.jpg 768w, http://idinheiro.local/wp-content/uploads/2020/09/amazon-prime-channels-554x416.jpg 554w, http://idinheiro.local/wp-content/uploads/2020/09/amazon-prime-channels.jpg 960w" data-ll-status="loaded">';
// https://regex101.com/r/OKsLfm/1/
preg_match('/\<img(?:.+?)src="([^"]+)/', $content, $matches);
$imageUrl = $matches[1];
var_dump($imageUrl); // http://idinheiro.local/wp-content/uploads/2020/09/amazon-prime-channels-300x225.jpg
更新
要在任何缩放完成之前获取原始文件名,您可以执行以下操作:
<?php
// Scaled image is saved with -<width>x<height> suffix.
$filename = 'amazon-prime-channels-300x225.jpg';
// Get rid of extension first.
$basename = pathinfo($filename, PATHINFO_FILENAME);
// strrpos() finds the position of the last occurring string '-'.
// Use substr() to grab everything from the start of the string (0) up to (exclusive!) the position
// of the last dash.
$origBasename = substr($basename, 0, strrpos($basename, '-'));
var_dump($origBasename); // string(21) "amazon-prime-channels"
推荐阅读
- android - 基于其子元素的可扩展背景图像
- c# - 实体框架核心 FromSQL 抛出 ArgumentNullException
- android - 在 SDK 中授予对 Activity UI 的控制权
- c++ - 哈希表 C++ 字符串
- angular-material - 如何使用角度材料中的自定义指令验证输入表单字段并显示错误?
- pattern-matching - Elixir 复杂模式匹配顺序
- jquery - 如何在 AEM Touch UI Dialog 中找到组件路径?
- java - /me in minecraft 没有被我写的插件禁用
- rest - 如何处理来自 REST 的多种类型的异常
- couchbase - 想在我的 CouchBase 中借助复合键插入数据但面临这个问题