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

时间:2012-09-26 15:20:05

标签: php

我正在尝试获取字符串的前10个字符,并希望用'_'替换空格。

我有

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

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

我想要字符串

  

这是对字符串的测试。

成为

  

this_is_th

5 个答案:

答案 0 :(得分:123)

只需使用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)));

答案 1 :(得分:5)

你可以尝试

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

var_dump($string);

输出

this_is_th

答案 2 :(得分:3)

只是做:

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

答案 3 :(得分:3)

这可能就是你所需要的:

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

答案 4 :(得分:2)

您首先需要剪切字符串中您想要的部分。然后更换您想要的部件:

var div = document.createElement("div");
div.innerHTML = "<!--[if lte IE 6]><i></i><![endif]-->";
var isIe6orLower = (div.getElementsByTagName("i").length == 1);

alert("Is IE 6 or lower: " + isIe6orLower);

这将输出:

  

this_is_th