这是一个例子:$original_string = 'I like apples very much. I want an apple.';$temp_string = str_replace('apples', '_apples_', $original_string);// $temp_string is now: I like _apples_ very much. I want an apple.$final_string = str_replace('apple', '_apple_', $temp_string);// $final_string is now: I like __apple_s_ very much. I want an _apple_.这不是我打算做的。我希望最终的字符串是:I like _apples_ very much. I want an _apple_.这就是我试图做的:$original_string = 'I like apples very much. I want an apple.';$final_string = str_replace(['apples', 'apple'], ['_apples_', '_apple_'], $original_string);echo $original_string;// I like __apple_s_ very much. I want an _apple_. 颠倒更换顺序也无济于事:$original_string = 'I like apples very much. I want an apple.';$original_string = str_replace(['apple', 'apples'], ['_apple_', '_apples_'], $original_string);echo $original_string;// I like _apple_s very much. I want an _apple_. 我应该怎么办?
1 回答
慕森卡
TA贡献1806条经验 获得超8个赞
您可以使用preg_replace它使用正则表达式而不是字符串进行替换
$original_string = 'I like apples very much. I want an apple.';
$final_string = preg_replace("/(apples?)/", "_$1_", $original_string);
echo $final_string;
正则表达式解释: https: //regex101.com/r/EzxqWR/2和演示: https: //3v4l.org/uTDIs
(1) (2)
vvvvvvvv vvvv
preg_replace("/(apples?)/", "_$1_", $original_string);
它将搜索字符串
apple
或apples
并将结果放入
$1
and 成为_apple_
or_apples_
希望解释清楚,对于不好的解释表示歉意
- 1 回答
- 0 关注
- 102 浏览
添加回答
举报
0/150
提交
取消