我想获取一个字符串的前10个字符,并将其中的空格替换为'_'
。
我的代码如下:
$text = substr($text, 0, 10);
$text = strtolower($text);
但我不确定接下来该怎么做。
我想要这个字符串:
this is the test for string.
变成
this_is_th
我想获取一个字符串的前10个字符,并将其中的空格替换为'_'
。
我的代码如下:
$text = substr($text, 0, 10);
$text = strtolower($text);
但我不确定接下来该怎么做。
我想要这个字符串:
this is the test for string.
变成
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)));
strtolower
和str_replace
的顺序没有关系,除非替换字符串依赖于大写或小写字符。 - Pharap$string = "this is the test for string." ;
$string = str_replace(' ', '_', $string);
$string = substr($string,0,10);
var_dump($string);
输出
this_is_th
这可能是你需要的:
$text = str_replace(' ', '_', substr($text, 0, 10));
只需执行:
$text = str_replace(' ', '_', $text)
首先需要将字符串分成您所需的几个部分,然后替换您想要的部分:
$text = 'this is the test for string.';
$text = substr($text, 0, 10);
echo $text = str_replace(" ", "_", $text);
(注:原文已为中文,无需翻译)this_is_th