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

我试图得到一个字符串的前10个字符,并希望用 '_'替换空格。

是的

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

但我不知道下一步该怎么办。

我要绳子

这是字符串测试。

成为

这就是

297828 次浏览

Simply use str_replace:

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

You would do this after your previous substr and strtolower calls, like so:

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

If you want to get fancy, though, you can do it in one line:

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

Just do:

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

You can try

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


var_dump($string);

Output

this_is_th

This is probably what you need:

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

You need first to cut the string in how many pieces you want. Then replace the part that you want:

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

This will output:

this_is_th