用php替换带下划线的空格[关闭]

问题描述 投票:0回答:3

这是一个非常新手的问题,但我无法弄清楚问题出在哪里,所以请耐心等待...

这就是我想要实现的目标 - > $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;
?> 
php replace
3个回答
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
投票

请允许我向您介绍str_replace()

$var = str_replace(' ', '_', $var);

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
© www.soinside.com 2019 - 2024. All rights reserved.