Page 1 of 1

matching keywords with preg_match

Posted: Wed Feb 24, 2010 4:02 pm
by lauthiamkok
Hi,
I am trying to match keywords only in a string like this,

Code: Select all

if (preg_match("(gif|jpg)", "jpge")) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}
and it returns - 'A match was found' which is not I want...

how should I write the expression so that it only match keywords like 'gif' and 'jpg', in other words, i dont want it to return true if the string has 'jpge', such as above.

many thanks,
Lau

Re: matching keywords with preg_match

Posted: Wed Feb 24, 2010 4:09 pm
by AbraCadaver
Depends on your criteria. If you want jpg or gif to be the end of the string, then:

Code: Select all

preg_match("/(gif|jpg)$/", "jpge");

Re: matching keywords with preg_match

Posted: Wed Feb 24, 2010 4:18 pm
by lauthiamkok
AbraCadaver wrote:Depends on your criteria. If you want jpg or gif to be the end of the string, then:

Code: Select all

preg_match("/(gif|jpg)$/", "jpge");
no sorry... i want them to be in any place in a string like this,

"this is a jpg format."

any ideas?

thanks.

Re: matching keywords with preg_match

Posted: Wed Feb 24, 2010 4:43 pm
by requinix

Code: Select all

/\b(gif|jpe?g)\b/
A \b is a word boundary.

Re: matching keywords with preg_match

Posted: Wed Feb 24, 2010 4:51 pm
by lauthiamkok
tasairis wrote:

Code: Select all

/\b(gif|jpe?g)\b/
A \b is a word boundary.
got it. thank u very much! :D