2

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

例如,我需要将所有空格 ( ) 和逗号 ( ,) 替换为加号 ( +) ,但一次不超过一个加号

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

会成为:the+quick+brown+fox+jumped+over+the+lazy+dog

4

2 回答 2

7

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

$text = 'the,quick, brown fox jumped, over the,, lazy, dog';
$newText = preg_replace('/[ ,+]+/', '+', $text);
于 2012-04-17T20:30:19.017 回答
2
<?php
echo preg_replace('/[, ]+/', '+', 'the,quick, brown fox jumped, over the,, lazy, dog') . PHP_EOL;
于 2012-04-17T20:32:03.227 回答