在第5场比赛后将char替换为null

时间:2012-08-01 09:44:05

标签: php

以下哪种方法最好?

# if I have the following string :
$str = "Foo Bar Foo Bar Foo Bar Foo Bar Foo Bar Foo Bar Foo Bar";
# and I want to remove "o" character after 5-th match so result I need is :
$newStr = "Foo Bar Foo Bar Fo Bar F Bar F Bar F Bar F Bar...";

我知道的方式:

  $str = "Foo Bar Foo Bar Foo Bar Foo Bar Foo Bar Foo Bar Foo Bar";
  $str = explode("o", $str);
  $new = "";
  $c = 1;
  foreach($str as $k) {
    if($c>5)
      $new .= $k;
    else 
      $new .= $k."o";
    $c++;
  }

我相信有更好的方法可以做到这一点。

1 个答案:

答案 0 :(得分:1)

必须有一百万种方法才能做到这一点。我快速浏览了内置函数,看看是否有strpos出现n th ,但没有。

这是 a 解决方案。它可能不是最好的,但谁知道。

$str = "Foo Bar Foo Bar Foo Bar Foo Bar Foo Bar Foo Bar Foo Bar";

for (
    $offset = 0, $count = 0;
    $count < 5;
    $offset = strpos($str, 'o', $offset) + 1, $count++
);

$newStr = substr($str, 0, $offset++) .
    str_replace('o', '', substr($str, $offset));

很抱歉疯狂的循环,最近做了太多的高尔夫代码!

这是另一种方法。

$str = "Foo Bar Foo Bar Foo Bar Foo Bar Foo Bar Foo Bar Foo Bar";

$newStr = implode('o', str_replace('o', '',  explode('o', $str, 6)));
相关问题