Tony
Tony

Reputation: 744

How to use preg_match()/preg_replace() on specific lengths and patterns

I'm having so much trouble understanding this, could someone explain it?

I'm extremely concerned about sanitizing data on my website and I'd like to go the extra mile and strip everything that's not supposed to be there. here's an example I end up handling a lot of hex values which only contain hyphens, numbers and letters A through F in a string like this

7d43637d-780c-4703-8467-13525d590

How would I go about writing a preg_match/replace that would check for 8 characters '0-9' 'A-F' 'a-f', hyphen, 4 chars, hyphen, 4 chars, hyphen, 4 chars, hyphen, 9 chars?

Would it go a bit like this?

pre_replace("/([0-9a-fA-F]{8})\/([-])\/([0-9a-fA-F]{4})\/([-])\/([0-9a-fA-F]{4})\/([-])\/([0-9a-fA-F]{4})\/([-])\/([0-9a-fA-F]{9})\", "", $string);

I'm sorry it's so long and confusing, I am definitely open to alternative ideas to accomplish this.

I also need one that will check 'A-Z' 'a-z' '0-9' '-' '_' and 32 characters long

I really wish there was an online generator for this, maybe if I can understand how it is done I'll build one for other poor souls.


Edit

Using AbraCadaver's code I was able to get this to work using

if(!preg_match("/[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{9}/i", $string)){
    echo 'error';
} else {
    //continue code
}

Upvotes: 0

Views: 272

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

You were close but have alot more than needed. Also, the i makes it case insensitive (A or a):

"/[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{9}/i"

Regular expression visualization

Debuggex Demo

if(!preg_match("/[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{9}/i", $string)) {
    echo "Invalid string";
}

Upvotes: 4

Related Questions