shotdsherrif
shotdsherrif

Reputation: 563

Regex Matching of Optional Character in PHP

I'm using PHP's regex preg_match() to try to match a string that occassionally contains a hyphen in the middle. The alphanumeric pattern is consistent: 3 letters followed by 3 numbers and one (optional) last letter Example:

RTE234
RTE-234  

OR

DGF123R
DGF-123R

My database saves the string without any dash, but the string's datasource is now starting to sometimes include it. So my pattern that had previously been working:

preg_match_all("/\b\(?([a-z0-9-]+)\)?\b/i", $subject, $matches);

needs to be adjusted, but I'm not exactly sure how to form the multi-bracketed string which allows for an optional hyphen. My first attempt ...

preg_match_all("/\b([a-z]{3}[-]?[a-z0-9-]+)\b/i", $subject, $matches);

As you see, I can be more detailed about the first 3 letters - [a-z]{3} - but the optional dash syntax is what I'm not sure about - [-]?

Any suggestions?

Upvotes: 2

Views: 5355

Answers (4)

Julien Spronck
Julien Spronck

Reputation: 15423

Since you probably want to save the string without any dash, you can do it in two groups:

preg_match_all('/\b(\w{3})-?(\d{3}\w?)\b/i', $subject, $matches);

and call the two subgroups to create the string without any dash:

$ubject2 = $matches[1].$matches[2];

Upvotes: 0

Michael Sivolobov
Michael Sivolobov

Reputation: 13240

you need next preg_match:

preg_match_all('/\b[a-z]{3}-?\d{3}[a-z]?\b/i', $subject, $matches);

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173552

The alphanumeric pattern is consistent: 3 letters followed by 3 numbers and one (optional) last letter

/[a-z]{3}\d{3}[a-z]?/

occassionally contains a hyphen in the middle

/([a-z]{3})-?(\d{3}[a-z]?)/

In code:

if (preg_match('/([a-z]{3})-?(\d{3}[a-z]?)/', $str, $matches)) {
    echo $matches[1] . $matches[2];
}

Upvotes: 0

AKDADEVIL
AKDADEVIL

Reputation: 206

A simple pattern that matches would be

"\b[a-z]{3}-?[0-9]{3}[a-z]?\b"

You do not need brackets for matching a single character like - in this case, just use a?, b*, c{3} or whatever you'd like to match.

Upvotes: 2

Related Questions