Forum Moderators: coopster

Message Too Old, No Replies

Find last occurance in a string

         

DrDoc

10:35 pm on Apr 11, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Is there a way I can match only the last occurance of a string in another string, as well as get the offset? Or, do I have to do this:

$string = "I like blue widgets.";
preg_match("/ [^ ]+/",$string);

Would that match only the last space in the sentence?

Fischerlaender

1:06 pm on Apr 12, 2003 (gmt 0)

10+ Year Member



You can use strrpos() to match the last occurance of a single character in a given string.
To match the last occurance of a string within another string, you could use strpos() in a loop and store the result with the biggest offset. (I'm sure there is a more sophisticated solution. *g*)

Your RegExp would match the first space that is followed by at least one non-space character.
$string = "I like blue widgets.";
Your RegExp would match " like", " blue" and " widgets."

preg_match("/ [^ ]+$/",$string);

This should only match the last occurance: " widgets."

DrDoc

4:26 pm on Apr 12, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Of course! Can't believe I overlooked strrpos... Thanks!





With "last space" I implied the following chars as well (" widgets.")... But in this case it doesn't matter, since I'm only interested in where the string starts.