首页 > 解决方案 > PHP preg_replace() 模式查找具有特定文件夹的 img

问题描述

我正在尝试用占位符替换博客文章 the_content() 中的损坏图像。我的媒体文件夹中的两个文件夹丢失,这导致图像损坏。

所以以下建议对我有用,我觉得

<?php 
$content = get_the_content();
$content = preg_replace("/<img[^>]+\>/i", "placeholderim", $content);          
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content); echo $content; ?>

但我想将模式与图像匹配,图像 URL 应包含 2017 || 2018. 如何创建这种模式。请提供任何帮助!

标签: regexwordpress

解决方案


这会查找所有包含 2019 或 2020 的 html 图像标签。

/(<img[^>]+(2019|2020)+[^>]+>)/ig

演示:https ://regex101.com/r/0rdwd2/1

对于 PHP(未经测试),这将是:

$content = get_the_content();
$content = preg_replace("/(<img[^>]+(2019|2020)+[^>]+>)/ig", "placeholderim", $content); 

推荐阅读