【问题标题】:PHP Preg Replace - Match String with Space - WordpressPHP Preg 替换 - 用空格匹配字符串 - Wordpress
【发布时间】:2026-01-15 00:40:02
【问题描述】:

我正在尝试扫描我的 wordpress 内容以查找:

<p><span class="embed-youtube">some iframed video</span></p>   

然后改成:

<p class="img_wrap"><span class="embed-youtube">some iframed video</span></p>  

在我的主题的function.php文件中使用以下代码:

$classes = 'class="img_wrap"';
$youtube_match = preg_match('/(<p.*?)(.*?><span class="embed-youtube")/', $content, $youtube_array);

if(!empty($youtube_match))
 {
  $content = preg_replace('/(<p.*?)(.*?><span class=\"embed-youtube\")/', '$1 ' . $classes . '$2', $content);
 }

但由于某种原因,我的正则表达式没有匹配,替换也没有工作。我不明白为什么没有匹配,因为存在类 embed-youtube 的跨度。

更新 - 这是完整的功能

function give_attachments_class($content){
   $classes = 'class="img_wrap"';
   $img_match = preg_match("/(<p.*?)(.*?><img)/", $content, $img_array);
   $youtube_match = preg_match('/(<p.*?)(.*?><span class="embed-youtube")/', $content, $youtube_array);

   // $doc = new DOMDocument;
   // @$doc->loadHTML($content); // load the HTML data

   // $xpath = new DOMXPath($doc);
   // $nodes = $xpath->query('//p/span[@class="embed-youtube"]');

   // foreach ($nodes as $node) {
   //    $node->parentNode->setAttribute('class', 'img_wrap');
   // }

   // $content = $doc->saveHTML();


   if(!empty($img_match))
    {
     $content = preg_replace('/(<p.*?)(.*?><img)/', '$1 ' . $classes . '$2', $content);
    }
   else if(!empty($youtube_match))
    {
     $content = preg_replace('/(<p.*?)(.*?><span class=\"embed-youtube\")/', '$1 ' . $classes . '$2', $content);
    }

   $content = preg_replace("/<img(.*?)src=('|\")(.*?).(bmp|gif|jpeg|jpg|png)(|\")(.*?)>/", '<img$1 data-original=$3.$4 $6>' , $content);

   return $content;
  }

add_filter('the_content','give_attachments_class');

【问题讨论】:

    标签: php regex wordpress


    【解决方案1】:

    不要使用正则表达式,而是有效地使用 DOMXPath 来为您执行此操作。

    $doc = new DOMDocument;
    @$doc->loadHTML($html); // load the HTML data
    
    $xpath = new DOMXPath($doc);
    $nodes = $xpath->query('//p/span[@class="embed-youtube"]');
    
    foreach ($nodes as $node) {
       $node->parentNode->setAttribute('class', 'img_wrap');
    }
    
    echo $doc->saveHTML();
    

    【讨论】:

    • 这并不完全适用于 wordpress。我在 wordpress 中使用 the_content(),我不想完整地拥有一个带有 doctype 等的新文档。我只想转换 the_content() 的 html 输出
    【解决方案2】:

    这是我为你做的一个快速而肮脏的正则表达式。它会找到以 p 标记开始、以 p 标记结尾、还包括跨度等的整个字符串。我还写了它来为您包含单引号或双引号,因为您永远不知道,并且还在各个地方包含空格。让我知道你的效果如何,谢谢。

    (<p )+(class=)['"]+img_wrap+['"](><span)+[ ]+(class=)+['"]embed-youtube+['"]>[A-Za-z0-9='" ]+(</span></p>)
    

    我已经在您的代码和其他一些变体上对其进行了测试,它对我有用。

    【讨论】:

    • 这个正则表达式如何适应 preg_match 和 preg_replace?我尝试添加它,但我似乎遇到了很多关于 ' 和 " 的语法问题
    • 当你在这个网站上测试时它会起作用。 regexr.com检查你的代码,我的正则表达式工作正常。
    • 为什么不止1个单/双引号['"]+?为什么[ ]+? OP 应该在哪里使用它? @JasonBiondo @hwnd 的答案对您不起作用,您是否出于某种原因需要正则表达式?
    • @chris85 - 查看我对 wordpress 的评论。