删除字符串开头的单词

时间:2013-06-21 03:19:24

标签: php regex string

$str = "hello world, what's up";

如何查看$str以查看是否有单词“hello”并仅在字符串的开头(前5个字母)处将其删除?

3 个答案:

答案 0 :(得分:3)

^表示字符串的开头,并根据@ Havenard的评论表示不区分大小写的匹配的i标志。

preg_replace('/^hello/i', '', $str);

答案 1 :(得分:2)

您可以使用substrfaster than preg_replace

$str = "hello world, what's up?";
$pre = "hello ";

if(substr($str, 0, strlen($pre)) === $pre)
    $str = substr($str, strlen($pre));

echo $str;    // world, what's up?

答案 2 :(得分:0)

preg_replace('/^hello\b/U', '', $str);

这将取代'hello world'中的'hello',而不是'helloworld'中的'hello'。因为它在字符串的开头只替换了一个实例,所以cpu的使用量可以忽略不计。

相关问题