【问题标题】:preg_replace Is it possible to replace everything in between two symbols?preg_replace 是否可以替换两个符号之间的所有内容?
【发布时间】:2014-09-21 23:34:28
【问题描述】:

我创建了一个模板系统,它替换了所有以“%%”开头和结尾的变量。问题是 preg replace 有时会替换更多,这是一个示例:

<?php
    $str  = "100% text %everythingheregone% after text";
    $repl = "test";
    $patt = "/\%([^\]]+)\%/"; 
    $res  = preg_replace($patt, "", $str);
    echo $res;
?>

这会输出“文本后 100”,它应该输出“文本后 100% 文本”。有什么解决办法吗?这真的很糟糕,因为如果文档中有 CSS 规则,则使用百分号并最终替换所有文档。

【问题讨论】:

    标签: php regex preg-replace


    【解决方案1】:

    使用否定的lookbehind 将所有% 符号匹配到数字后面不存在的符号。

    (?<!\d)%([^%]*)\%
    

    然后将匹配的字符串替换为空字符串。

    DEMO

    $str  = "100% text %everythingheregone% after text";
    $repl = "test";
    $patt = "/(?<!\d)%([^%]*)\%\s*/"; 
    $res  = preg_replace($patt, "", $str);
    echo $res;
    

    输出:

    100% text after text
    

    【讨论】:

      【解决方案2】:

      如果这是您要求的,您可以使用此正则表达式找到两个 % 符号中的 (并替换掉):

      /.*\K%[^%]+%/
      

      这是regex demo

      【讨论】:

        【解决方案3】:

        这个问题是一个错误的设计,不应该用一些漂亮的正则表达式来解决。考虑为占位符使用唯一标识符,并且仅从允许的变量名称列表中匹配。

        $str = "100% text {%_content_%}";

        并使用str_replace()替换

        $res = str_replace("{%_content_%}", "test", $str);
        

        strtr() 进行多次替换:

        $replace_map = array(
        "{%_content_%}" => "test",
        "{%_foo_%}" => "bar",
        );
        
        $res = strtr($str, $replace_map);
        

        只是一个针对核心问题的想法。


        到那时替换%containing_word_characters%

        $res = preg_replace('~%\w+%~', "test", $str);
        

        test at regex101

        【讨论】:

        • 太棒了!令人难以置信的是,您注意到有关单词字符的要点。我想了一会儿,然后认为可能不是这样。
        猜你喜欢
        • 1970-01-01
        • 2021-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-28
        • 1970-01-01
        相关资源
        最近更新 更多