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.
strpos in PHP is a built-in function. Its use is to find the first occurrence of a substring in a string or a string inside another string. The function returns an integer value which is the index of the first occurrence of the string.
Answer: Use the PHP strpos() Function You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false .
The strpos() function finds the position of the first occurrence of a string inside another string. The stripos() function finds the position of the first occurrence of a string inside another string. 2. It is case-sensitive function.
The strrpos() function finds the position of the last occurrence of a string inside another string. Note: The strrpos() function is case-sensitive. Related functions: strpos() - Finds the position of the first occurrence of a string inside another string (case-sensitive)
You can make use of strrpos
function for this:
$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
or a regex based solution as:
if(preg_match("#$key$#",$str)) {
print "$str ends in $key"; // prints Oh, hi O ends in O
}
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:
$theWord = "my word";
$theWordLen = strlen($theWord);
$theString = "hello myword";
$matches = ($theWord ==substr($theString, -1 * $theWordLen);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With