JayGatz
JayGatz

Reputation: 271

Replace different instances of the same character at different string positions

I am trying to do the following in PHP and would greatly appreciate any and all help.

  1. store the location of each instance of a character in a string in an array
  2. use a for loop to navigate the array and replace the character at each position, each element in the array, with another character.

Here is what I have so far:

$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 */
}

I know str_replace would do just this, but I want to learn how to do this the above mentioned way.

Upvotes: 0

Views: 105

Answers (2)

Orangepill
Orangepill

Reputation: 24645

  <?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;
  }

Upvotes: 0

laurent
laurent

Reputation: 90776

Just iterate over each character and store the position. Then iterate over these positions and set the character.

for ($i = 0; $i < strlen($string1); $i++) {
    if ($string1[$i] == $character1) $characterPositions[] = $i;
}

foreach ($characterPositions as $position){
    $string1[$position] = $character2;
}

Upvotes: 1

Related Questions