WP替换嵌套在某些类中的列表项

我正在尝试将html标记添加到具有特定类的无序列表中。

这将是以以下内容开头的HTML:

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>    
<ul class="foo">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

最后, 我想得出:

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>    
<ul class="foo">
  <li><svg class="icon"><use xlink:href="#foo"></use></svg>Item 1</li>
  <li><svg class="icon"><use xlink:href="#foo"></use></svg>Item 2</li>
  <li><svg class="icon"><use xlink:href="#foo"></use></svg>Item 3</li>
</ul>

我还没有找到可用于运行preg_replace()使其能够正常工作的正则表达式。

内容是使用Wordpress创建的。我想使用过滤器来扫描the_content并添加额外的标记。以这种方式:

function foo_ul($text) {
    //some function
    return $text;
}
add_filter('the_content', 'foo_ul');

我不想依赖Javascript / jQuery, 因此希望在服务器端生成。

有任何想法吗?


#1


正如你所看到的那样, 使用正则表达式匹配HTML是不好的。但是, 如果你的字符串是你在OP中显示的字符串, 则可以使用此正则表达式模式选择<li> </ li>之间的每个字符串, 然后向其中添加目标字符串。

$newHtml = preg_replace("/(?<=<li>)(.*)(?=<\/li>)/", '<svg class="icon"><use xlink:href="#foo"></use></svg>$1', $html);

在演示中检查结果


更新:如果你有多个ul, 并且只想匹配.foo, 请使用此代码

$newHtml = preg_replace_callback("/(?<=<ul\sclass=\"foo\">).*?(?=<\/ul>)/s", function($ma){
    return preg_replace("/(?<=<li>)(.*)(?=<\/li>)/", '<svg class="icon"><use xlink:href="#foo"></use></svg>$1', $ma[0]);
}, $html);

在演示中检查结果

来源:

https://www.srcmini02.com/63848.html

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_37563.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?