WESTKINz
WESTKINz

Reputation: 257

Creating a regular expression that would match a string

I'm trying to create a regular expression that would match a string. I am adding a multiple condition, starting with 'f', followed by any number of characters, followed by letter 'a' or the character '-', followed by one or more numeric characters and followed by the letter 'n'

The following examples should return true:

So far I have researched php regular expression and created this code

$a = 'f2bfv-2009n';

$f_search = 'f';
$num_search = '[0-9]';
$or_search = '(a|-)';
$double_number_search = "^[0-9]{1,}$";
$n_search = 'n';

if(preg_match("/{$or_search}{$double_number_search}{$f_search}{$num_search}{$n_search}/i", $a)) {
      echo 'true';
}

This should be true but its not

Upvotes: 2

Views: 50

Answers (1)

MH2K9
MH2K9

Reputation: 12039

Your pattern (a|-)^[0-9]{1,}$f[0-9]n which is formed wrongly. You started with a or - and the line start symbol ^ and end symbol $ are at the middle position which are wrong. I formed it correctly as per your demand. Try the following regex.

$a = 'f2bfv-2009n';
if(preg_match("/^f\w+(a|-)\d+n/i", $a)) {
    echo 'true';
}

Working Demo

Upvotes: 1

Related Questions