gpt4 book ai didi

php - 使用 strpos 将单词匹配到字符串的末尾

转载 作者:可可西里 更新时间:2023-11-01 13:58:13 24 4
gpt4 key购买 nike

解决方案:strpos 结果证明是最有效的。可以使用 substr 来完成,但这会创建一个临时子字符串。也可以使用正则表达式来完成,但比 strpos 慢,并且如果单词包含元字符,则并不总是产生正确的答案(请参阅 Ayman Horieh 评论)。

选择的答案:

if(strlen($str) - strlen($key) == strrpos($str,$key))
print "$str ends in $key"; // prints Oh, hi O ends in O

最好测试严格相等===(见大卫回答)

感谢大家的帮助。


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

基本上 if $theWord = "my word";

$theString = "hello myword";        //match
$theString = "myword hello"; //not match
$theString = "hey myword hello"; //not match

最有效的方法是什么?

附言在标题中我说了 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com