SOLVED: preg_match find last word of a string

All your question about php
Post Reply
mister_v
Posts: 199
Joined: Thu Mar 04, 2010 9:19 pm

SOLVED: preg_match find last word of a string

Post 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 :-(
Last edited by mister_v on Thu Oct 01, 2015 6:58 pm, edited 1 time in total.
chris
Site Admin
Posts: 205
Joined: Mon Jul 21, 2008 9:52 am

Re: preg_match find last word of a string

Post 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 .
mister_v
Posts: 199
Joined: Thu Mar 04, 2010 9:19 pm

Re: preg_match find last word of a string

Post by mister_v »

Thanks a lot :-)
Post Reply