0

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"

2 Answers 2

5

I will suggest using:

/\b\w+(?=\W*$)/m

RegEx Demo

This will match last word optionally followed by 0 or more non-word characters like period. (See demo)

Sign up to request clarification or add additional context in comments.

Comments

1

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.

DEMO

$re = "/\\w+$/m";
$str = "This is a file (USA) -LastWord\nThis is another file (EUR) ~LastWord\nThis is another different file (JPN) LastWord";
preg_match_all($re, $str, $matches);

3 Comments

Doesn't seem to be returning any results.
explanation that $ is end of string and \w is a-z group, + is one or more char, you're missing i modifier
you must need to add multiline modifier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.