用一个`-`替换多个`-`而不用正则表达式

Ada*_*iss 1 php regex

我见过很多RegExp的误用,我真的不喜欢它:)

我有字符串(由于两个str_replaces)可能看起来像这样:

.?This iš my ".stRiNg."!
          |
          V
--this-is-my---string---
Run Code Online (Sandbox Code Playgroud)

有没有比这更好的方法

$string = trim(preg_replace('/[-]+/u','-', $string),'-');
Run Code Online (Sandbox Code Playgroud)

要得到:

this-is-my-string
Run Code Online (Sandbox Code Playgroud)

mač*_*ček 8

preg_replace()获胜

<?php

function benchmark($callback){
  echo sprintf('%-30s: ', $callback);
  $t = microtime(true);
  foreach(range(1, 10000) as $n){
    call_user_func($callback);
  }
  echo (microtime(true)-$t)."\n";
}

function implode_explode_filter(){
  implode('-', array_filter(explode('-', '--this-is-my---string---')));
}

function preg_replace_trim(){
  preg_replace('/-+/', '-', trim('--this-is-my---string---', '-'));
}

function brant(){
  $parts = explode("-",'--this-is-my---string---');
  for($i=0;$i<count($parts);$i++) {
      if (strlen($parts[$i]) < 1) {
          unset($parts[$i]);
      }
  }
  reset($parts);
  $string = implode("-",$parts);
}

function murze_bisko(){
  $string = "--this-is-my---string---";
  while (strpos($string, "--") !== false) {
    $string = str_replace("--", "-", $string);
  }
  $string = trim($string, '-'); # both of their answers were broken until I added this line
}

benchmark('implode_explode_filter');
benchmark('preg_replace_trim');
benchmark('brant');
benchmark('murze_bisko');

# Output
# implode_explode_filter        : 0.062376976013184
# preg_replace_trim             : 0.038193941116333
# brant                         : 0.11686086654663
# murze_bisko                   : 0.058025121688843
?>
Run Code Online (Sandbox Code Playgroud)


GSt*_*Sto 5

我不明白你为什么要寻找一种"更好"的方式.你的方式在一个非常适合的地方使用一个简单的正则表达式.还有什么比那个更好呢?