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

Rou*_*uge 79 php

我试图获取字符串的前10个字符,并希望用空格替换空格'_'.

我有

  $text = substr($text, 0, 10);
  $text = strtolower($text);
Run Code Online (Sandbox Code Playgroud)

但我不知道下一步该做什么.

我想要字符串

这是对字符串的测试.

成为

this_is_th

Jon*_*hop 139

只需使用str_replace:

$text = str_replace(' ', '_', $text);
Run Code Online (Sandbox Code Playgroud)

您可以在之前substr和之后进行此操作strtolower,如下所示:

$text = substr($text,0,10);
$text = strtolower($text);
$text = str_replace(' ', '_', $text);
Run Code Online (Sandbox Code Playgroud)

但是,如果你想获得幻想,你可以在一行中完成:

$text = strtolower(str_replace(' ', '_', substr($text, 0, 10)));
Run Code Online (Sandbox Code Playgroud)

  • 我发现“花式”版本更易于阅读。值得注意的是,除非替换字符串取决于小写或大写字符,否则“ strtolower”和“ str_replace”的顺序无关紧要。 (3认同)

Bab*_*aba 7

你可以试试

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

var_dump($string);
Run Code Online (Sandbox Code Playgroud)

产量

this_is_th
Run Code Online (Sandbox Code Playgroud)


Zat*_*ter 5

这可能就是您所需要的:

$text = str_replace(' ', '_', substr($text, 0, 10));
Run Code Online (Sandbox Code Playgroud)