替换 PHP 中的字符,但不要超过一次


Replace characters in PHP but no more than once

某些字符替换为最多一个其他字符的最佳脚本是什么?

例如,我需要将所有空格 () 和逗号 ( + ) 替换为加号 ( the,quick, brown fox jumped, over the,, lazy, dog ),但一次不超过一个加号

所以:the+quick+brown+fox+jumped+over+the+lazy+dog

会变成:CC_5

我会为此使用正则表达式:

$text = 'the,quick, brown fox jumped, over the,, lazy, dog';
$newText = preg_replace('/[ ,+]+/', '+', $text);
<?php
echo preg_replace('/[, ]+/', '+', 'the,quick, brown fox jumped, over the,, lazy, dog') . PHP_EOL;