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

How can replace multiple strings on same line or not in same line with PHP?

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

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

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

好的,基本上您需要做的就是寻找一组花括号并将其替换,加上其中的所有内容。

像这样的东西应该适合你:

<?php

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

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

print $fileContent;    

表达式的含义如下 \{.*?\}:

  • \{ - 寻找左花括号 {。我们需要用反斜杠转义它 \ 因为花括号在正则表达式中有特殊含义。
  • .*? - 匹配任意字符 .,任意次数 *,直到我们到达语句的下一部分 ?.
  • \} - 我们语句的下一部分是右花括号 }。同样,我们需要用反斜杠转义它 \.

这是一个工作演示:

http://ideone.com/Pi8OvI

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

<?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;