91

我正在尝试获取字符串的前 10 个字符,并希望将空格替换为'_'.

我有

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

但我不确定下一步该做什么。

我想要字符串

这是对字符串的测试。

变得

this_is_th

4

5 回答 5

170

只需使用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)));
于 2012-09-26T15:21:52.233 回答
8

你可以试试

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

var_dump($string);

输出

this_is_th
于 2012-09-26T15:22:53.043 回答
5

这可能是您需要的:

$text = str_replace(' ', '_', substr($text, 0, 10));
于 2012-09-26T15:23:15.553 回答
4

做就是了:

$text = str_replace(' ', '_', $text)
于 2012-09-26T15:22:31.030 回答
2

你需要先把绳子剪成你想要的几根。然后替换你想要的部分:

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

这将输出:

this_is_th

于 2015-09-23T04:55:47.943 回答