Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match md5 hashes

Tags:

What type of regex should be used to match a md5 hash.

how to validate this type of string 00236a2ae558018ed13b5222ef1bd987

i tried something like this: ('/^[a-z0-9]/') but it didnt work.

how to achieve this? thanks

like image 743
mwweb Avatar asked Feb 02 '14 22:02

mwweb


People also ask

How do you match MD5?

Type the following command: md5sum [type file name with extension here] [path of the file] -- NOTE: You can also drag the file to the terminal window instead of typing the full path. Hit the Enter key. You'll see the MD5 sum of the file. Match it against the original value.

How do I check if a string is MD5 hash?

You can check using the following function: function isValidMd5($md5 ='') { return preg_match('/^[a-f0-9]{32}$/', $md5); } echo isValidMd5('5d41402abc4b2a76b9719d911017c592'); The MD5 (Message-digest algorithm) Hash is typically expressed in text format as a 32 digit hexadecimal number.

What does this regex do?

Short for regular expression, a regex is a string of text that lets you create patterns that help match, locate, and manage text. Perl is a great example of a programming language that utilizes regular expressions. However, its only one of the many places you can find regular expressions.


2 Answers

This is a PCRE that will match a MD5 hash:

define('R_MD5_MATCH', '/^[a-f0-9]{32}$/i');  if(preg_match(R_MD5_MATCH, $input_string)) {     echo "It matches."; } else {     echo "It does not match."; } 
like image 151
Ryan Avatar answered Dec 14 '22 23:12

Ryan


Try ctype_xdigit:

<?php  $hash = '00236a2ae558018ed13b5222ef1bd987';  var_dump(strlen($hash) === 32 && ctype_xdigit($hash)); 

Output: bool(true)

like image 35
Dave Chen Avatar answered Dec 14 '22 23:12

Dave Chen