Tag Archives: regular expression

2 regular expression code snippets a developer needs daily

Regular expression can be easily called the heart of data mining technology. For beginners it may look like a very hard thing to grasp, But actually it’s pretty simple and compact once it’s been learned.

I have listed some pretty basic regular expressions here , Which can help in mining nearly 70% of the text available on the web.

1) Validate username, consist of alpha-numeric (a-z, A-Z, 0-9), underscores, and has minimum 5 character and maximum 20 character. You could change the minimum character and maximum character to any number you like.

$username = "user_name12";
if (preg_match('/^[a-zd_]{5,20}$/i', $username)) {
    echo "Your username is ok.";
} else {
    echo "Wrong username format.";
}

2) Need to highlight repeating words in the text, This regex can become very handy.

$text = "This is a sample test written by Gaurav Mishra This is a sample test written by Gaurav Mishra This is a sample test written by Gaurav Mishra This is a sample test written by Gaurav Mishra This is a sample test written by Gaurav Mishra"; 
$text = preg_replace("/b(Gaurav)b/i", '<span style="background:#5fc9f6">1</span>', $text);
echo $text;

3)