【问题标题】:How to replace particular Substring within a String using PHP preg_replace如何使用 PHP preg_replace 替换字符串中的特定子字符串
【发布时间】:2015-06-07 08:40:14
【问题描述】:

我正在尝试使用preg_replace 替换字符串中的单词或单词序列? 例如:

改变这些:

ABCExample to abcExample
AnotherExample to anotherExample
XyzAbcExample to xyzAbcExample

保持原样:

xyzExample to xyzExample 
new to new

【问题讨论】:

标签: php regex string replace preg-replace


【解决方案1】:

你需要使用preg_replace_callback函数。

$str = <<<EOT
ABCExample
AnotherExample
XyzAbcExample
xyzExample
new
EOT;
echo preg_replace_callback('~(?m)^[A-Za-z]*?(?=(?:[A-Z][a-z]+)+$)~', function ($m)
        { 
            return strtolower($m[0]);
        }, $str);

【讨论】:

    【解决方案2】:

    我猜你正在寻找str_ireplace

    此函数返回一个字符串或数组,其中所有出现的 在主题中搜索(忽略大小写)替换为给定的替换 价值。如果您不需要花哨的替换规则,通常应该 使用此函数代替带有 i 修饰符的 preg_replace()。

    示例代码(和sample program):

    $res1 = str_ireplace("abc", "xyz", "ABCExample to abcExample");
    echo $res1;
    

    输出:xyzExample to xyzExample

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      • 2019-03-30
      • 2020-02-15
      • 2011-01-29
      • 2012-09-04
      相关资源
      最近更新 更多