这是一个非常新手的问题,但我无法弄清楚问题出在哪里 所以请耐心等待......
这是我想要实现的目标 - > $new = 'OMG_This_Is_A_One_Stupid_Error';
这是我从此代码中获得的内容 - > $new = 'OMG This Is A One Stupid_Error';
<?php
$find = 'OMG This Is A One Stupid Error'; //just an example
$offset = 0;
$search = ' ';
$length = strlen($search);
$replace = '_';
while($substring = strpos($find, $search,$offset))
{
$new = substr_replace($find, $replace,$substring,$length);
$offset = $substring + $search_length;
}
echo $new;
?>
答案 0 :(得分:6)
使用str_replace()功能:
<?php
$old = 'OMG_This_Is_A_One_Stupid_Error';
$new = str_replace(' ', '_', $old);
echo $old; // will output OMG This Is A One Stupid error
?>
反转参数以获得反向效果
<?php
$old = 'OMG This Is A One Stupid_Error';
$new = str_replace('_', ' ', $old);
echo $old; // will output OMG_This_Is_A_One_Stupid error
?>
答案 1 :(得分:1)
请允许我向您介绍str_replace()
$var = str_replace(' ', '_', $var);
答案 2 :(得分:0)
您可以使用str_replace
如果您只是希望源字符串将下划线替换为空格,请使用:
$source = 'OMG This Is A One Stupid Error'; //just an example
// $new is: OMG_This_Is_A_One_Stupid_Error
$new = str_replace(' ', '_', $source);
如果源字符串是较大字符串的子字符串,则可以执行此操作:
$source = 'This is a question for SO. '
. 'OMG This Is A One Stupid Error';
$to_replace = 'OMG This Is A One Stupid Error';
$target = str_replace(' ', '_', $to_replace);
// Finally replace the target string
$new = str_replace($to_replace, $target, $source)
// $new is: This is a question for SO. OMG_This_Is_A_One_Stupid_Error