views:

57

answers:

3

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.

A: 

You could use a regular expression.

if(preg_match('/'.$theWord.'$/', $theString)) {
    //matches at the end of the string
}

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.

jjclarkson
Doesn't produce the correct output if `$theWord` contains meta-characters. Try it with `$theWord` set to `'.'` for example.
Ayman Hourieh
Quite true, you'd definitely have to validate the word and/or escape meta-characters.
jjclarkson
It's probably slower than codaddict's first method too.
Brendan Long
+1  A: 

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
}
codaddict
The regex solution doesn't always produce correct results. See my comment on @jjclarkson's answer.
Ayman Hourieh
@Ayman, thanks for pointing it out. Will update the summary of the thread.
clover
@Aryam: OP wants to match a word not just any string. Now I've assumed a word will be alphabetic or alphanumeric. If the word can contain any char of which some can be regex meta char, this will not work and we'll have to escape the metas.
codaddict
+1  A: 

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);
David
The disadvantage of this method is that you are creating a temporary string from the "substr" result. The strrpos method mentioned by codaddict is probably faster (although you would want to test strict equality).
David