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.

Comments 3

  • 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);
    
  • 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.

发表评论

电子邮件地址不会被公开。 必填项已用*标注