首页 > 解决方案 > 正则表达式查找 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;

?>

标签: phpregex

解决方案


您可以使用此正则表达式来获取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"

推荐阅读