如何使用 substr_replace 在字符串的多个位置替换或插入一个字符,我可以在函数上添加多个位置吗?

How to replace or insert a character on multiple locations on a string using substr_replace, can I add more than one position on the function?

正如标题所说

我想在字符串中插入或替换逗号 (,)。

我有这个字符串:A 适合 B 适合 C 适合 D。我想在每个适合的后面和适合之前的单词之后插入逗号。

这是想要的结果:A, fits B, Fits C, Fits D

我用来实现的代码是:

$newstr = substr_replace($oldstr,", ",stripos($oldstr,"fits")-1,0);

但是,此代码仅在第一次出现的“fits”处插入 1 个逗号。 我尝试使用 substr_count() 来计算匹配次数,然后使用 For loop 但逗号堆叠在第一次出现匹配的位置。

像这样:A,,, Fits B Fits C Fits D

必须有一种方法可以达到预期的结果,它必须在 substr_replace() 函数中添加多个位置或其他正确的方法?

编辑

我的字符串是White Fits Black Fits Red Fits Blue 期望的结果是 White, Fits Black, Fits Red, Fits Blue

逗号 , 位于字符串中每个 Fits 单词的后面,并且紧跟在 fits

后面的单词之后

我的问题的关键点是:如何在每个 fits 单词后面和 fits

后面的单词后面加上逗号

先致谢

使用preg_replace:

$input = "A fits B Fits C Fits D";
$output = preg_replace("/\b([A-Z]+)(?=\s)/", ",", $input);
echo $input . "\n" . $output;

这会打印:

A fits B Fits C Fits D
A, fits B, Fits C, Fits D

下面是对正则表达式模式的解释:

\b([A-Z]+) 匹配并捕获前面的一个或多个大写字母 通过单词边界 (?=\s) 然后断言后面是一个 space;这可以防止最终 被分配逗号的字母,如果输入以字母结尾

然后,我们用 </code> 替换捕获的字母,后跟一个逗号。</p> <p><strong>编辑:</strong></p> <p>对于您最近的编辑,您可以使用:</p> <pre><code>$input = "White Fits Black Fits Red Fits Blue"; $output = preg_replace("/\b(?=\s+Fits\b)/", ",", $input); echo $input . "\n" . $output;

这会打印:

White Fits Black Fits Red Fits Blue
White, Fits Black, Fits Red, Fits Blue