Jump to content

Here are some useful RegEx everyone can use... I'll add more with time.


mattkenefick

Did you find these useful?  

1 member has voted

  1. 1. Did you find these useful?

    • Yes
      0
    • No
      0
    • Somewhat
      0
    • I love polls
      1


Recommended Posts

Search Multiple Words

if( preg_match( "/\s+((word1)|(word2))\s+/" , $str ) )
{
   print "Found: " . $str;
}

 

Find word variations

if( preg_match( "/Joh?n(athan)? Johnson/" , $str ) )
{
   print "Found: " . $str;
}

 

Find Similar Words ( finds bat,cat,mat,rat )

if( preg_match( "/\b[bcmr]at\b/" , $str ) )
{
   print "Found: " . $str;
}

 

 

Find lines that begin with...

if( preg_match( "/^Word\b/" , $str ) )
{
   print "Found: " . $str;
}

 

 

 

Lines that END with...

if( preg_match( "/\bword$/" , $str ) )
{
   print "Found: " . $str;
}

 

 

Escape Quotes

$str = $_POST['value'];
return preg_replace( '/(^|(?<!\\\))\"/', '\\\"', $str );

 

 

 

Drop Lines in file

$str = $_POST['value'];
return ereg_replace( ',[[:space:]]*', ',<br />', $str);

 

 

Extract Queries from URLs

if ( ereg( '^[^?]*\?(.*)$', $str, $matches) )
{
    echo "Found: $matches[1]";
}

 

 

Format US Date

$date = $_POST['date'];
$newDate = preg_replace( "/^(\d{1,2})[-\/.]?(\d{1,2})[-\/.]?((?:\d{2}|\d{4}))$/", "$1-$2-$3", $date);
print $newDate;

 

 

Validate Social Security Numbers

$socialNumber = $_POST['value'];
if (preg_match( "/^00[1-9]|0[1-9]\d|[1-5]\d{2}|6[0-5]\d|66[0-5]|66[7-9]|6[7-8]\d|690|7[0-2]\d|73[0-3]|750|76[4-9]|77[0-2])-(?!00)\d{2}-(?!0000)\d{4}$/", $socialNumber) )
return "Its real";

 

 

 

 

If you have any requests, let me know!

There are many things to consider:

 

1. You have parentheses that are not needed and cause the engine to work harder.

2. Not bad, but the lack of word boundaries or whitespace could match more than you'd like.

3. In a rare instance you might encounter a word or variation thereof that uses an apostrophe; this would trigger the word boundary.

4. OK, but keep #3 in mind. If you search for /^Can\b/ you'll find "Can" even though the first word may be "Can't."

5. #3 and #4 still apply, but the chance of this breaking should be much more difficult. Be careful with $ because it's not a true end of line--that's \z.

 

Case insensitivity needs to be considered for all of these as well.

 

That's all the review I have for now...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.