【发布时间】:2017-05-14 06:31:33
【问题描述】:
用一个程序在不使用str_replace的情况下替换字符串中的子字符串
应该是通用函数应该适用于以下示例:
字:你好,世界 替换词:llo 替换为:zz 输出应该是:Hezz world
字:你好,世界 替换单词:o 替换为:xx 输出应该是:Hellxx wxxrld
这是我为解决它而写的
function stringreplace($str, $stringtoreplace, $stringreplaceby){
$i=0;$add='';
while($str[$i] != ''){
$add .= $str[$i];
$j=0;$m=$i;$l=$i;$check=0;
if($str[$i] == $stringtoreplace[$j]){
while($stringtoreplace[$j] != ''){
if($str[$m] == $stringtoreplace[$j]){
$check++;
}
$j++;$m++;
}
if($check == strlen($stringtoreplace)){
$n=0;$sub='';
for($n=0;$n<=strlen($stringtoreplace);$n++){
$str[$l] = '';
$sub .= $str[$l];
$l++;
}
$add .= $stringreplaceby;
$i += $check;
}
}
$i++;
}//echo $add;exit;
return $add;
}
我得到了 helzzworld 的输出。 请看看我做错了什么,或者如果您对此有更好的解决方案,请提出建议。
【问题讨论】:
-
你可以试试这个... preg_replace():
-
@Learning strlen 是否允许? :D
-
如果我们不使用它会很好。
-
你想在不使用 strlen 等内置函数的情况下解决这个问题吗?
标签: php arrays string algorithm