如何用PHP替换同一行上的多个字符串或不在同一行中?

时间:2016-01-13 16:31:19

标签: php preg-replace brackets

需要正则表达式用myReplace替换所有内部括号!重要的是需要保留空格和行!

$fileContent = <div class="panel-body">
    {toChangeOne}{toChangeTwo}
                            {  
                    toChangeTree
                    }
</div>

$change = preg_replace('NEEDED_REGEX', 'myReplace', $fileContent);

2 个答案:

答案 0 :(得分:2)

好的,基本上所有你需要做的就是寻找一组花括号并替换它,加上其中的所有东西。

这样的事情对你有用:

<?php

$fileContent = '<div class="panel-body">
    {toChangeOne}{toChangeTwo}
                            {  
                    toChangeTree
                    }
</div>';

$fileContent = preg_replace('~\{.*?\}~sm', 'myReplace', $fileContent);

print $fileContent;    

这里的表达式意味着\{.*?\}

  • \{ - 寻找一个大括号{。我们需要用反斜杠\来逃避它,因为花括号在正则表达式中具有特殊含义。
  • .*? - 匹配任何字符.,任意次*,直到我们点击语句?的下一部分。
  • \} - 我们陈述的下一部分是结束大括号}。同样,我们需要使用反斜杠\来逃避它。

这是一个有效的演示:

http://ideone.com/Pi8OvI

答案 1 :(得分:1)

您还可以使用一组键来解决您的问题,如下所示进行更改。尝试替换多个字符串时,这可能会有所帮助。

<?php

// array with keys that you'll be changing in your text
$toChange = array(
"{toChangeOne}" => "First Change",
"{toChangeTwo}" => "Second Change",
"{toChangeThree}" => "Third Change"
);


$fileContent = '<div class="panel-body">
    {toChangeOne}{toChangeTwo}
                            { 
                    toChangeThree
                    }
</div>';

// loop through all the keys you want to change
foreach($toChange as $key => $value){

    // prep regex
    // remove the openning and curly braces this 
    // way we can match anything that matches our 
    // keys even if there's a mixture of returns 
    // or empty spaces within the curly braces 
    $key_text = str_replace("{", "", $key);
    $key_text = str_replace("}", "", $key_text);

    // "\{"             - matches the character "{" literally
    // "(\s|\s+)?"      - matches any white space. In our case 
    //                    we might want it to be optional hense 
    //                    the "?"
    // "\}"             - matches the character "}" literally   
    $regex = '/\{(\s|\s+)?'.$key_text.'(\s|\s+)?\}/';

    $fileContent = preg_replace($regex, $value, $fileContent);
}

echo $fileContent;