0

这是一个非常新手的问题,但我就是不知道问题出在哪里,所以请多多包涵...

这就是我想要实现的目标-->$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;
?> 
4

3 回答 3

7

使用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
?>
于 2012-09-17T14:08:44.417 回答
1

请允许我向您介绍str_replace()

$var = str_replace(' ', '_', $var);
于 2012-09-17T14:08:53.277 回答
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
于 2012-09-17T14:14:50.010 回答