2012-09-26 28 views
40

我想獲取字符串的前10個字符,並且想用'_'替換空格。如何替換PHP中的一部分字符串?

$text = substr($text, 0, 10); 
    $text = strtolower($text); 

但我不知道下一步該怎麼做。

我希望字符串

這是字符串的考驗。

成爲

this_is_th

+0

http://php.net/str_replace –

+0

http://php.net/manual /en/function.str-replace.php – Smamatti

回答

78

只需使用str_replace

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

後您以前substrstrtolower電話你會做到這一點,像這樣:

$text = substr($text,0,10); 
$text = strtolower($text); 
$text = str_replace(' ', '_', $text); 

如果你想要漂亮的,不過,你可以做一個行:

$text = strtolower(str_replace(' ', '_', substr($text, 0, 10))); 
+6

請不要幻想。 – Dave

3

只要做到:

$text = str_replace(' ','_',$text) 
3

您可以嘗試

$string = "this is the test for string." ; 
$string = str_replace(' ', '_', $string); 
$string = substr($string,0,10); 

var_dump($string); 

輸出

this_is_th 
3

這可能是你所需要的:

$text=str_replace(' ', '_', substr($text,0,10)); 
0

您需要先削減你要多少件的字符串。然後替換所需的部分:

$text = 'this is the test for string.'; 
$text = substr($text, 0, 10); 
echo $text = str_replace(" ", "_", $text); 

這將輸出:

this_is_th

相關問題