preg_match question

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
bobb
Forum Newbie
Posts: 18
Joined: Sun Jun 28, 2009 3:41 am

preg_match question

Post by bobb »

I am experimenting, and doing the following:

Code: Select all

<?
if(preg_match('_'.preg_quote("Charlotte[/ ]([0-9a-z.]{1,10})", '_').'_', "Mozilla/5.0 (compatible; Charlotte/1.0t; http://www.searchme.com/support/)")) {
 
    echo "<br>A match was found.";
} else {
    echo "<br>A match was not found.";
}
?>
But this returns :A match was not found... How is this possible? I want to have A match was found, but I don't know where my fault is in my code... is it in the

Code: Select all

 
Charlotte[/ ]([0-9a-z.]{1,10})
 

part?

thanks
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: preg_match question

Post by prometheuzz »

bobb wrote:I am experimenting, and doing the following:

Code: Select all

<?
if(preg_match('_'.preg_quote("Charlotte[/ ]([0-9a-z.]{1,10})", '_').'_', "Mozilla/5.0 (compatible; Charlotte/1.0t; http://www.searchme.com/support/)")) {
 
    echo "<br>A match was found.";
} else {
    echo "<br>A match was not found.";
}
?>
But this returns :A match was not found... How is this possible? I want to have A match was found, but I don't know where my fault is in my code... is it in the

Code: Select all

 
Charlotte[/ ]([0-9a-z.]{1,10})
 

part?

thanks
Because there is no sub-string:

Code: Select all

Charlotte[/ ]([0-9a-z.]{1,10})
in your target string (because of the preg_quote(...), the regex meta characters are escaped and loose their special powers, so to speak). In other words, don't use preg_quote(...):

Code: Select all

if(preg_match('_Charlotte[/ ]([0-9a-z.]{1,10})_', "Mozilla/5.0 (compatible; Charlotte/1.0t; http://www.searchme.com/support/)")) {
    echo "<br>A match was found.";
} else {
    echo "<br>A match was not found.";
}
Post Reply