2

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:

  • f2a20n
  • f2bfv-2009n
  • f2-2000n
  • f2bfv-2009na

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

wow it works. Earlier I tried this method on my own and it didn't work. I must have missed some symbols. Thank you
I was missing \w+ and \ what do they represent @MH2K9
\w+ search for word characters in a string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.