【问题标题】:Replace unique character to array将唯一字符替换为数组
【发布时间】:2015-10-16 20:51:44
【问题描述】:

我需要用字符数组替换主题上所有出现的#。例如:

Input: "#### #### #### ####"
Search character: "#"
Replacement array: [ 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3 ]
Expected result:  "0000 1111 222 3333"

我尝试使用:

str_replace("#", $array, $subject)

但它并没有像我想要的那样工作。有什么想法吗?

【问题讨论】:

  • 代码是用什么语言编写的?
  • 等等,你有一个带有一些“#”的string,你想用array替换每个“#”?
  • PHP。是的,除非我有更好的方法。
  • @DavidRodrigues 那么这个问题我们在哪里?

标签: php arrays string replace


【解决方案1】:

您可以使用preg_replace_callback() 并访问您的替换数组并将每个匹配项替换为一个新元素,例如

<?php

    $input = "#### #### #### ####";
    $replacement = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3];
    $key = 0;
    $output = preg_replace_callback("/#/", function($m)use(&$key, $replacement){
        if(isset($replacement[$key]))
            return $replacement[$key++];
        else
            return $replacement[$key = 1];
    }, $input);

    echo $output;

?>

输出:

0000 1111 2222 3333

【讨论】:

  • 请解释反对意见,以便我改进我的答案。我认为我的回答向 OP 展示了如何做他想做的事。
  • @Rizier123:删除 $key+1 并且它工作正常/编辑:看起来你修复了它就像我评论的那样
  • @splash58 更新代码后没有注意到。感谢您的通知。
【解决方案2】:

为什么一个简单的 for 循环不能解决问题?

function replacer($array,$item, $subject){

   foreach($array as $character)
      $subject=preg_replace('/'.$item.'/',$character,$subject,strlen($item));

   return $subject;
}

测试

$input = "#### #### #### ####";
$replacement = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3];

echo replacer($replacement, '#',$input);

输出

0000 1111 2222 3333

【讨论】:

  • 为什么一个简单的 for 循环不能解决问题? 很可能,因为这会抛出一个错误并且也不起作用:3v4l.org/65Yeq
  • 说真的谁赞成这个?它甚至不起作用并引发错误!
  • 是的。我知道。一些编辑太快了,发布得太快了。它现在应该可以工作了。
【解决方案3】:

我用一个简单的for 解决了这个问题。

$subject = "#### #### #### ####";
$numbers = "0000111122223333"; // I could use array, instead
$numbersLength = strlen($numbers);

for ($i = 0; $i < $numbersLength; $i++) {
    $subject = preg_replace("/#/", $numbers[$i], $subject, 1);
}

我不认为这是一个优雅的解决方案,但似乎 PHP 没有本地方法来做到这一点。

【讨论】:

    猜你喜欢
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    • 1970-01-01
    • 2021-04-18
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多