【问题标题】:preg_replace with regex searching for question marks inside h[1-6]-Tagspreg_replace 用正则表达式搜索 h[1-6]-Tags 中的问号
【发布时间】:2014-08-24 11:43:09
【问题描述】:

我使用的 Google 字体 (Amatic SC) 在他的粗体版本中显示 ® 符号而不是问号。

为了解决这个问题,我想使用 preg_replace在我的 $content h1-h6 内搜索任何类型的问号 (?,¿)标签(我只在标题中使用这种字体)并将它们包装在一个额外的 span 元素中以分配它们不同的类,以便我可以使用普通版本而不是字体的粗体版本。

由于我对正则表达式不太熟悉,因此我很难做到这一点。我不知道如何只搜索问号并将它们包装在一个额外的跨度内。

function.php 中的当前 Wordpress 代码:

function replace_content($content){
    $regex = '#(<h([1-6])[^>]*>)\s?(.*)?\s?(<\/h\2>)#';
    $content = preg_replace($regex,'\1<span class="normal">\3</span>\4',$content);
    return $content;
}
add_filter('the_content','replace_content');

函数应该替换类似这样的标记:

<h1>¿This is a questions?</h1>

用这个:

<h1><span class="normal">¿</span>This is a questions<span class="normal">?</span></h1>

【问题讨论】:

    标签: php regex wordpress preg-replace


    【解决方案1】:

    如果你想在这里使用一个正则表达式(与常见的模因相反,它完全适合众所周知的输出)你应该最好使用两个。这允许将上下文与实际目标分开:

    $regex = '#(<h([1-6])[^>]*>)([^<>]+)(<\/h\2>)#';
    $content = preg_replace_callback($regex, function($match) {
        return
            "$match[1]"
          . preg_replace("/[¿?]/u", "<span class='normal'>$0</span>", $match[3])
          . "$match[4]";
    }, $content);
    

    preg_replace_callback 将整个标题传递给替换函数。 [¿?] 匹配您要查找的字符。 (匿名函数需要 PHP 5.3)

    另一种选择是仅使用 CSS 进行字体替换。
    http://www.w3.org/TR/css3-fonts/#composite-fonts

    @font-face {
      font-family: "Amatic SC";
      src: url(fonts/amatic.ttf);
      unicode-range: U+00-3E, U+40-7F;
    }
    

    这将使您字体字符范围之外的符号无论如何都回退到默认字体。

    【讨论】:

      【解决方案2】:

      如果您对使用正则表达式感到满意,您可以在此处使用级联回调函数。

      $text = <<<DATA
      <h1>¿This is a questions?</h1>
      <h2>¿This is a questions?</h2>
      <h3>¿This is a questions?</h3>
      DATA;
      
      $text = preg_replace_callback('~<h([1-6])>[^<]++</h\1>~', 
            function($m) {
               return preg_replace('~[¿?]~u', '<span class="normal">$0</span>', $m[0]);
            }, $text);
      

      输出

      <h1><span class="normal">¿</span>This is a questions<span class="normal">?</span></h1>
      <h2><span class="normal">¿</span>This is a questions<span class="normal">?</span></h2>
      <h3><span class="normal">¿</span>This is a questions<span class="normal">?</span></h3>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-01-23
        • 2011-05-20
        • 2016-07-11
        • 2023-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多