[英]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
,但逗号堆叠在第一次出现拟合的 position 中。
像这样: A,,, Fits B Fits C Fits D
必须有一种方法来达到预期的结果,它必须在substr_replace()
function 中添加多个 position 还是什么?
编辑
我的字符串是White Fits Black Fits Red Fits Blue
所需的结果是White, Fits Black, Fits Red, Fits Blue
逗号,
放在字符串中每个Fits
单词的后面,并且紧跟在fits
后面的单词之后
我的问题的关键是: fits
在每个fits
单词后面加上逗号,并且紧跟在 fit 后面的单词之后
之前谢谢
使用preg_replace
:
$input = "A fits B Fits C Fits D";
$output = preg_replace("/\b([A-Z]+)(?=\s)/", "$1,", $input);
echo $input . "\n" . $output;
这打印:
A fits B Fits C Fits D
A, fits B, Fits C, Fits D
以下是正则表达式模式的解释:
\b([AZ]+) 匹配并捕获一个或多个大写字母,它们前面有一个单词边界 (?=\s) 然后断言后面是一个空格; 如果输入以字母结尾,这可以防止最后一个字母被分配一个逗号
然后,我们用$1
替换捕获的字母,后跟逗号。
编辑:
对于您最近的编辑,您可以使用:
$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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.