Page 1 of 1

SOLVED: preg_match find last word of a string

Posted: Fri Aug 21, 2015 9:18 pm
by mister_v
Hi,

I want to use preg_match() too find the last word of a string:

I already have this:

Code: Select all

$content='just a string';
$pattern = '/[\w]+$/';
preg_match($pattern, $content, $result);
echo $result[0];
but it doesn't work :-(

Re: preg_match find last word of a string

Posted: Sat Aug 22, 2015 10:45 am
by chris
In this case it might be easier to use explode()

Code: Select all

explode(' ',$content);

But if you really want to use preg_match()

Code: Select all

$content='just a string';
$pattern='/[a-z]+(?=[^a-z]*$)/i';
preg_match($pattern, $content, $result);
explanation:
/ # pattern delimiter
[a-z]+ # all characters between a and z at least one or more times
(?= # open a lookahead. Means followed by:
[^a-z]* # all characters that are not letters zero or more times
$ # until the end of the string
) # close the lookahead
/ # pattern delimiter
i # case insensitive ( [a-z] => [a-zA-Z] and [^a-z] => [^a-zA-Z])

It gets the last word even if at the end of the string there is a ? or .

Re: preg_match find last word of a string

Posted: Thu Oct 01, 2015 6:57 pm
by mister_v
Thanks a lot :-)