PHP正则表达式-查找并用连字符替换主题标签下划线

时间:2019-06-14 09:22:19

标签: php wordpress preg-replace

我有一个锚标签href链接,如下所示:

<a href="#_what_are_classes">What are classes</a>

使用正则表达式替换

<a href="#what-are-classes">What are classes</a>

以相同的方式将DIV更改为

<div id="_what_are_classes" class="padTop"></div>

使用正则表达式

<div id="what-are-classes" class="padTop"></div>

2 个答案:

答案 0 :(得分:1)

此函数替换了您提到的HTML属性,但是您可能需要在提供的示例之外对HTML属性进行调整:

<?php

function convert_hrefs_and_ids($text) {
    $replace = static function($str) {
        $prefix = str_replace('_', '', $str[2]);
        $attribute = str_replace('_', '-', $str[3]);
        return $str[1] . '="' . $prefix . $attribute . '"';
    };
    $text = preg_replace_callback('/(a.+href)="(#_)([a-z0-9_]+)"/Ui', $replace, $text);
    $text = preg_replace_callback('/(div.+id)="(_)([a-z0-9_]+)"/Ui', $replace, $text);
    return $text;
}

如果您想将其与Wordpress一起使用,可以看看Wordpress API for content filters并像这样使用它:

<?php

add_filter('the_content', 'convert_hrefs_and_ids');

答案 1 :(得分:1)

这将替换所有<a href和所有包含下划线的<div id

$string = '<a href="#_what_are_classes">What are classes</a>

   <div id="_what_are_classes" class="padTop"></div>';

$res = preg_replace_callback(
            '/(?:<a.*?href="|<div.*?id=")\K[^"]+/',
            function ($m) {
                // remove the # and _ at the beginning
                // then replace _ with -
                return str_replace('_','-',preg_replace('/^#?_/', '', $m[0]) );
            },
            $string);
echo $res;

输出:

<a href="what-are-classes">What are classes</a>

   <div id="what-are-classes" class="padTop"></div>

说明:

(?:                 # start non capture group
    <a.*?href="     # a href
  |                 # OR
    <div.*?id="     # div id
)                   # end group
\K                  # forget all we have seen until this posiiton
[^"]+               # 1 or more not quote