matching a word to end of string with strpos
Solution:
strpos
turned out to be the most efficient. Can be done with substr
but that creates a temporary substring. Can also be done with regex, but slower than strpos and does not always produce the right answer if the word contains meta-characters (see Ayman Hourieh comment).
Chosen answer:
if(strlen($str) - strlen($key) == strrpos($str,$key))
print "$str ends in $key"; // prints Oh, hi O ends in O
and best to test for strict equality ===
(see David answer)
Thanks to all for helping out.
I’m trying to match a word in a string to see if it occurs at the end of that string. The usual strpos($theString, $theWord);
wouldn’t do that.
Basically if $theWord = "my word";
$theString = "hello myword"; //match
$theString = "myword hello"; //not match
$theString = "hey myword hello"; //not match
What would be the most efficient way to do it?
P.S. In the title I said strpos
, but if a better way exists, that’s ok too.
相关推荐:
Multiple working directories with Git?
How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?
“Use Strict” and the applicable scope [duplicate]
Creating a lead programmatically in CRM Online
White screen of death codeigniter Error Reporting ON
What are the disadvantages to declaring Scala case classes?
Inferring type of generic implicit parameter from return type
Redis高级功能 - 慢查询日志
You can make use of
strrpos
function for this:or a regex based solution as:
strpos could be the most efficient in some cases, but you can also substr with a negative value as the second parameter to count backwards from the end of the string:
You could use a regular expression.
Or you could use strrpos() and add the length of the word. (strrpos — “Find position of last occurrence of a char in a string“) Then see if that is the position of the last character in the string.