替换同一字符在不同字符串位置的不同实例


Replace different instances of the same character at different string positions

我正在尝试用PHP做以下事情,非常感谢任何和所有的帮助。

  1. 将字符串中每个字符实例的位置存储在数组
  2. 使用for循环来导航数组,并用另一个字符替换数组中每个位置和每个元素的字符。

到目前为止我写的是:

$character1="/";
$character2="%";
$string1="hello / how / are / you / doing";
$characterPositions = array();
/* store locations of $character1 in $string1 */
foreach($characterPositions as $position){
    /* replace what is at each $position in string $string1 */
}

我知道str_replace会做到这一点,但我想学习如何做到这一点,上面提到的方式

只需遍历每个字符并存储位置。然后遍历这些位置并设置字符。

for ($i = 0; $i < strlen($string1); $i++) {
    if ($string1[$i] == $character1) $characterPositions[] = $i;
}
foreach ($characterPositions as $position){
    $string1[$position] = $character2;
}
  <?php
  $character1="/";
  $character2="%";
  $string1="hello / how / are / you / doing";
  $characterPositions = array();
  /* store locations of $character1 in $string1 */
  $lastOffset = 0;
  while (($pos = strpos($string1, $character1, $lastOffset+1)) !== FALSE){
        echo $lastOffset;
        $characterPositions[] = $pos;
        $lastOffset = $pos;
  }
  print_r($characterPositions);
  foreach ($characterPositions as $v){
        $string1[$v] = $character2;
  }