matching keywords with preg_match

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
lauthiamkok
Forum Contributor
Posts: 153
Joined: Wed Apr 01, 2009 2:23 pm
Location: Plymouth, United Kingdom

matching keywords with preg_match

Post 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
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: matching keywords with preg_match

Post 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");
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
lauthiamkok
Forum Contributor
Posts: 153
Joined: Wed Apr 01, 2009 2:23 pm
Location: Plymouth, United Kingdom

Re: matching keywords with preg_match

Post 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.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: matching keywords with preg_match

Post by requinix »

Code: Select all

/\b(gif|jpe?g)\b/
A \b is a word boundary.
lauthiamkok
Forum Contributor
Posts: 153
Joined: Wed Apr 01, 2009 2:23 pm
Location: Plymouth, United Kingdom

Re: matching keywords with preg_match

Post 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
Post Reply