在 HTML 代码中将 title 属性值移动到 class 属性值 [英] Move title attribute value to class attribute value in the HTML code

查看:25
本文介绍了在 HTML 代码中将 title 属性值移动到 class 属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个带有 HTML 的变量 $menu(没有循环,它来自一个函数).

We have variable $menu with HTML inside (there is no loop, it comes from a function).

echo 上,它给出了这样的代码:

On echo it gives the code like this:

<ul id="menu">
    <li id="some-id" class="many classes"><a title="one" href="#">text</a></li>
    <li id="some-id" class="many classes"><a href="#">text</a></li>
    <li id="some-id" class="many classes"><a title="three" href="#">text</a></li>
</ul>

我想做什么:

  1. 获取每个链接的title=""的值,并将其移动到父

  2. 类的末尾.
  1. get value of the title="" of each link, and move it to the end of parent <li> class.

从每个链接中删除 title="".

变量$menu中的代码应该变成:

Code inside variable $menu should become:

<ul id="menu">
    <li id="some-id" class="many classes one"><a href="#">text</a></li>
    <li id="some-id" class="many classes"><a href="#">text</a></li>
    <li id="some-id" class="many classes three"><a href="#">text</a></li>
</ul>

解决方案是什么?

推荐答案

这不是一个完美的解决方案,但它在我的测试 (Regex Buddy & XAMPP) 中使用了您的示例代码.

It's not a perfect solution, but it has worked in my testing (Regex Buddy & XAMPP) with your sample code.

$pattern = '/(<li [^>]*)(?:class=(?:"([^"]+)"|\'([^\']+)\'))([^>]*><a[^>]*)(?:title=(?:"([^"]+)"|\'([^\']+)\'))\s([^>]*>)(.*?<\/li>)/im';
$replace = '$1class="$2 $5"$4$7$8';

preg_replace( $pattern , $replace , $menu );

这篇关于在 HTML 代码中将 title 属性值移动到 class 属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆