2012-09-17 66 views
0

這是一個非常新手的問題,但我就是想不通問題出在哪裏 所以請原諒......更換用下劃線空間用PHP

這裏就是我想實現 - >$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

你可能想查找http://php.net/manual/en/function.str-replace .php – andrewsi

+2

http://php.net/str-replace或者換句話說:你不僅重新發明了輪子,而且還用火和石頭殺死了動物的食物;) – KingCrunch

+0

@KingCrunch :)) –

回答

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(混合$搜索,混合$替換,混合$主題[,詮釋和$計數])」 –

+0

抱歉,錯過了這個問題 –

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