【发布时间】:2013-06-21 11:38:02
【问题描述】:
$str = "hello world, what's up";
如何检查$str 以查看是否有单词“hello”,并且仅当它位于字符串的开头(前5 个字母)时才将其删除?
【问题讨论】:
-
你错过了
;;-) 做“正确”。 -
只是 "A" 可能的欺骗?天哪,字面上肯定有成千上万!
$str = "hello world, what's up";
如何检查$str 以查看是否有单词“hello”,并且仅当它位于字符串的开头(前5 个字母)时才将其删除?
【问题讨论】:
; ;-) 做“正确”。
你可以使用substr,也就是faster thanpreg_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?
【讨论】:
strlen($pre) 两次?将其保存在变量中。或者在这种情况下,为什么不直接将其设为 5?
^ 表示字符串的开头,i 标志用于根据@Havenard 的注释进行不区分大小写的匹配。
preg_replace('/^hello/i', '', $str);
【讨论】:
/i 标志以进行不区分大小写的匹配。
preg_replace('/^hello\b/U', '', $str);
这将替换“hello world”中的“hello”,但不会替换“helloworld”中的“hello”。因为它只替换字符串开头的一个实例,所以 cpu 使用量可以忽略不计。
【讨论】:
/U?你不使用量词!不过\b 是个好主意。我你很热,你可以删除之后的空间。