Reputation: 271
I am trying to do the following in PHP and would greatly appreciate any and all help.
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
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
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