如何在PHP中替换部分字符串?
2022-08-30 07:54:37
我正在尝试获取字符串的前10个字符,并希望将空格替换为.'_'
我有
$text = substr($text, 0, 10);
$text = strtolower($text);
但我不知道下一步该怎么办。
我想要字符串
这是对字符串的测试。
成为
this_is_th
我正在尝试获取字符串的前10个字符,并希望将空格替换为.'_'
我有
$text = substr($text, 0, 10);
$text = strtolower($text);
但我不知道下一步该怎么办。
我想要字符串
这是对字符串的测试。
成为
this_is_th
只需使用str_replace:
$text = str_replace(' ', '_', $text);
您可以在之前的和呼叫之后执行此操作,如下所示:substr
strtolower
$text = substr($text,0,10);
$text = strtolower($text);
$text = str_replace(' ', '_', $text);
但是,如果您想获得花哨,可以在一行中完成:
$text = strtolower(str_replace(' ', '_', substr($text, 0, 10)));
您可以尝试
$string = "this is the test for string." ;
$string = str_replace(' ', '_', $string);
$string = substr($string,0,10);
var_dump($string);
输出
this_is_th