代码之家  ›  专栏  ›  技术社区  ›  davewoodhall

PHP preg_match在某些元素中忽略

  •  1
  • davewoodhall  · 技术社区  · 6 年前

    我正在写一封信 regex 我需要过滤内容以格式化它的排版。到目前为止,我的代码似乎正在使用 preg_replace <pre> .

    作为参考,这将在WordPress的 the_content

    function my_typography( $str ) {
        $ignore_elements = array("code", "pre");
    
        $rules = array(
            "?" => array("before"=> "&thinsp;", "after"=>""),
            // the others are stripped out for simplicity
        );
    
        foreach($rules as $rule=>$params) {
            // Pseudo :
            //    if( !in_array( $parent_tag, $ignore_elements) {
            // /Pseudo
    
    
            $formatted = $params['before'] . $rule . $params['after'];
            $str = preg_replace( $rule, $formatted, $str );
    
    
            // Pseudo :
            //    }
            // /Pseudo
        }
    
        return $str;
    }
    add_filter( 'the_content',  'my_typography' );
    

    基本上:

    <p>Was this filtered? I hope so</p>
    <pre>Was this filtered? I hope not.</pre> 
    

    应该成为

    <p>Was this filtered&thinsp;? I hope so</p>
    <pre>Was this filtered? I hope not.</pre>
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   anubhava    6 年前

    您需要在中使用正则表达式分隔符包装搜索正则表达式 preg_replace preg_quote 转义所有特殊正则表达式字符,如 ? . , * + 等:

    $str = preg_replace( '~' . preg_quote($rule, '~') . '~', $formatted, $str );
    

    完整代码:

    function my_typography( $str ) {
        $ignore_elements = array("code", "pre");
    
        $rules = array(
            "?" => array("before"=> "&thinsp;", "after"=>""),
            // the others are stripped out for simplicity
        );
    
        foreach($rules as $rule=>$params) {
            // Pseudo :
            //    if( !in_array( $parent_tag, $ignore_elements) {
            // /Pseudo
    
    
            $formatted = $params['before'] . $rule . $params['after'];
            $str = preg_replace( '~' . preg_quote($rule, '~') . '~', $formatted, $str );
    
    
            // Pseudo :
            //    }
            // /Pseudo
        }
    
        return $str;
    }
    

    <p>Was this filtered&thinsp;? I hope so</p>
    <pre>Was this filtered&thinsp;? I hope not.</pre>