使用strpos将单词与字符串结尾匹配

clo*_*ver 5 php string

解决方案: 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
Run Code Online (Sandbox Code Playgroud)

并且最好测试严格的平等===(参见David回答)

感谢所有人的帮助.


我正在尝试匹配字符串中的单词以查看它是否出现在该字符串的末尾.通常strpos($theString, $theWord);不会这样做.

基本上如果 $theWord = "my word";

$theString = "hello myword";        //match
$theString = "myword hello";        //not match
$theString = "hey myword hello";    //not match
Run Code Online (Sandbox Code Playgroud)

最有效的方法是什么?

PS在我所说的标题中strpos,但如果存在更好的方法,那也没关系.

cod*_*ict 6

您可以使用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
Run Code Online (Sandbox Code Playgroud)

或基于正则表达式的解决方案:

if(preg_match("#$key$#",$str)) {
 print "$str ends in $key"; // prints Oh, hi O ends in O
}
Run Code Online (Sandbox Code Playgroud)