PHP Preg - 替换多个下划线

jku*_*ner 5 php regex preg-replace

我如何使用preg_replace用一个下划线替换多个下划线?

sou*_*rge 19

+运营商相匹配的最后一个字符(或捕获组)的多个实例.

$string = preg_replace('/_+/', '_', $string);
Run Code Online (Sandbox Code Playgroud)


che*_*rtz 9

preg_replace('/[_]+/', '_', $your_string);

  • 这里不需要字符类。一些解释将是对这个答案的一个很好的补充。 (2认同)

Che*_*tah 7

实际上使用/__+/或者/_{2,}//_+/使用单个下划线不需要更换更好.这将提高preg变体的速度.


GZi*_*ipp 5

运行测试,我发现了这个:

while (strpos($str, '__') !== false) {
    $str = str_replace('__', '_', $str);
}
Run Code Online (Sandbox Code Playgroud)

始终比这更快:

$str = preg_replace('/[_]+/', '_', $str);
Run Code Online (Sandbox Code Playgroud)

我生成了不同长度的测试字符串:

$chars = array_merge(array_fill(0, 50, '_'), range('a', 'z'));
$str = '';
for ($i = 0; $i < $len; $i++) {  // $len varied from 10 to 1000000
    $str .= $chars[array_rand($chars)];
}
file_put_contents('test_str.txt', $str);
Run Code Online (Sandbox Code Playgroud)

并使用这些脚本进行测试(单独运行,但对于$ len的每个值在相同的字符串上运行):

$str = file_get_contents('test_str.txt');
$start = microtime(true);
$str = preg_replace('/[_]+/', '_', $str);
echo microtime(true) - $start;
Run Code Online (Sandbox Code Playgroud)

和:

$str = file_get_contents('test_str.txt');
$start = microtime(true);
while (strpos($str, '__') !== false) {
    $str = str_replace('__', '_', $str);
}
echo microtime(true) - $start;
Run Code Online (Sandbox Code Playgroud)

对于较短的字符串,str_replace()方法比preg_replace()方法快25%.字符串越长,差异越小,但str_replace()总是更快.

我知道有些人比速度更喜欢一种方法而不是另一种方法,我很乐意阅读关于结果,测试方法等的评论.