解决方案:strpos
证明是最有效的。可以用substr
完成,但是会创建一个临时子字符串。也可以使用正则表达式来完成,但是比strpos慢,并且如果单词包含元字符,则总不能给出正确的答案(请参见Ayman Hourieh注释)。
选择答案:
if(strlen($str) - strlen($key) == strrpos($str,$key))
print "$str ends in $key"; // prints Oh, hi O ends in O
最好测试严格相等的
===
(请参阅David答案)感谢所有人的帮助。
我正在尝试匹配字符串中的单词,以查看它是否出现在该字符串的末尾。通常的
strpos($theString, $theWord);
不会这样做。基本上如果
$theWord = "my word";
$theString = "hello myword"; //match
$theString = "myword hello"; //not match
$theString = "hey myword hello"; //not match
什么是最有效的方法?
P.S.在标题中,我说了
strpos
,但是如果存在更好的方法,那也是可以的。 最佳答案
您可以为此使用 strrpos
函数:
$str = "Oh, hi O";
$key = "O";
if(strlen($str) - strlen($key) == strrpos($str,$key))
print "$str ends in $key"; // prints Oh, hi O ends in O
或基于正则表达式的解决方案为:
if(preg_match("#$key$#",$str)) {
print "$str ends in $key"; // prints Oh, hi O ends in O
}
关于php - 用strpos将一个单词匹配到字符串的末尾,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2528295/