在 PHP 中第一次替换后停止替换字符串中的文本

这是一个例子:


$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_. 

我应该怎么办?


呼唤远方
浏览 103回答 1
1回答

慕森卡

您可以使用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      vvvvpreg_replace("/(apples?)/", "_$1_", $original_string);它将搜索字符串apple或apples并将结果放入$1and 成为_apple_or_apples_希望解释清楚,对于不好的解释表示歉意
打开App,查看更多内容
随时随地看视频慕课网APP