Match word to end of line with strpos

Solution: strpos proved to be the most effective. It can be done using substr, but creates a temporary substring. It can also be done with a regular expression, but slower than strpos, and does not always give the correct answer if the word contains metacharacters (see Ayman Hourieh Comment).

Selected Answer:

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

and it is better to check strict equality ===(see David's answer)

Thank you all for your help.


I am trying to match a word in a line to see if this is happening at the end of this line. Normal strpos($theString, $theWord);won't do it.

In principle, if $theWord = "my word";

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

What would be the most effective way to do this?

PS In the title, I said strpos, but if there is a better way, this is also normal.

+5
3

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
}
+5

strpos , substr :

$theWord = "my word";
$theWordLen = strlen($theWord);

$theString = "hello myword";
$matches = ($theWord ==substr($theString, -1 * $theWordLen);
+1

.

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

strrpos() . (strrpos - " char " ) , .

0

All Articles