如何在PHP中替换字符串的一部分?

91

我想获取一个字符串的前10个字符,并将其中的空格替换为'_'

我的代码如下:

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

但我不确定接下来该怎么做。

我想要这个字符串:

this is the test for string.

变成

this_is_th


http://php.net/manual/en/function.str-replace.php - Smamatti
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)));

3
我发现“花哨版”更容易阅读。需要注意的是,strtolowerstr_replace的顺序没有关系,除非替换字符串依赖于大写或小写字符。 - Pharap

8
你可以尝试。
$string = "this is the test for string." ;
$string = str_replace(' ', '_', $string);
$string = substr($string,0,10);

var_dump($string);

输出

this_is_th

5

这可能是你需要的:

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

4

只需执行:

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

2

首先需要将字符串分成您所需的几个部分,然后替换您想要的部分:

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

这将输出:

this_is_th

(注:原文已为中文,无需翻译)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接