如何使用 PHP preg_replace 替换字符串中的特定子字符串
How to replace particular Substring within a String using PHP preg_replace
我正在尝试使用 preg_replace
替换字符串中的单词或单词序列?
例如:
更改这些:
ABCExample to abcExample
AnotherExample to anotherExample
XyzAbcExample to xyzAbcExample
保持原样:
xyzExample to xyzExample
new to new
我猜你正在寻找 str_ireplace
。
This function returns a string or an array with all occurrences of
search in subject (ignoring case) replaced with the given replace
value. If you don't need fancy replacing rules, you should generally
use this function instead of preg_replace() with the i modifier.
示例代码(和 sample program):
$res1 = str_ireplace("abc", "xyz", "ABCExample to abcExample");
echo $res1;
输出:xyzExample to xyzExample
您需要使用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);
我正在尝试使用 preg_replace
替换字符串中的单词或单词序列?
例如:
更改这些:
ABCExample to abcExample
AnotherExample to anotherExample
XyzAbcExample to xyzAbcExample
保持原样:
xyzExample to xyzExample
new to new
我猜你正在寻找 str_ireplace
。
This function returns a string or an array with all occurrences of search in subject (ignoring case) replaced with the given replace value. If you don't need fancy replacing rules, you should generally use this function instead of preg_replace() with the i modifier.
示例代码(和 sample program):
$res1 = str_ireplace("abc", "xyz", "ABCExample to abcExample");
echo $res1;
输出:xyzExample to xyzExample
您需要使用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);