0

I need get string follow this format (C-001 and C-001-C)

C-001 (match)
C-002C (not match)
C-003-C (match)
D-004 (not match)

This is my code

if(preg_match("/^C-[0-9]$/", $input_line, $output_array)) {
    print_r($output_array);
} else {
    echo "NOT MATCH";
}

But result show 3 string (C-001, C-002C, C-003-C), C-002C is wrong, how to fix it?

0

1 Answer 1

1

In your current regex you are looking for C- followed by 1 digit. If you want 3 digits you should use [0-9]{3}

^C-[0-9]{3}$

If you want to also allow another -C you can use (-C)? (the question mark is there as an optional group:

^C-[0-9]{3}(-C)?$

Here is a working example:
https://regex101.com/r/0JHN43/1

And this one is inside the preg_match block you have:

if(preg_match("/^C-[0-9]{3}(-C)?$/", $input_line, $output_array)) {
Sign up to request clarification or add additional context in comments.

Comments

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.