I'm trying to find out how to get the last word of a string, However the character im trying to match it too isn't always the same. For example
This is a file (USA) -LastWord
This is another file (EUR) ~LastWord
This is another different file (JPN) LastWord
How can i match against this? I always want to just return "LastWord"
I will suggest using:
/\b\w+(?=\W*$)/m
This will match last word optionally followed by 0 or more non-word characters like period. (See demo)
You could try the below regex to get the last word.
\w+$
$
matches the end of a line. \w+
matches one or more word characters. Add multiline m
modifier whenever anchors are used.
$re = "/\\w+$/m";
$str = "This is a file (USA) -LastWord
This is another file (EUR) ~LastWord
This is another different file (JPN) LastWord";
preg_match_all($re, $str, $matches);