dongniaoli1822 2015-05-26 00:50
浏览 46

PHP Preg替换 - 匹配字符串与空间 - Wordpress

I'm trying to scan my wordpress content for:

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

and then change it into:

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

using the following code in my function.php file in my theme:

$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);
 }

but for some reason I am not getting a match on my regex nor is the replace working. I don't understand why there isn't a match because the span with class embed-youtube exists.

UPDATE - HERE IS THE FULL FUNCTION

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');

  • 写回答

2条回答 默认 最新

  • douwen7475 2015-05-26 01:00
    关注

    Instead of using regex, make effective use of DOM and XPath to do this for you.

    $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();
    
    评论

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)