2012-09-26 29 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

相关问题