小编clo*_*ver的帖子

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

解决方案: 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,但如果存在更好的方法,那也没关系.

php string

5
推荐指数
1
解决办法
7929
查看次数

标签 统计

php ×1

string ×1