我正在尝试在PHP中执行以下操作,并非常感谢任何和所有帮助。
这是我到目前为止所做的:
$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会做到这一点,但我想学习如何以上述方式做到这一点。
答案 0 :(得分:1)
迭代每个角色并存储位置。然后迭代这些位置并设置角色。
for ($i = 0; $i < strlen($string1); $i++) {
if ($string1[$i] == $character1) $characterPositions[] = $i;
}
foreach ($characterPositions as $position){
$string1[$position] = $character2;
}
答案 1 :(得分:0)
<?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;
}