Skip to content

Instantly share code, notes, and snippets.

@evgv
Last active September 14, 2017 07:38
Show Gist options
  • Save evgv/2ba9e494492ff0fba8a143bc969cd06e to your computer and use it in GitHub Desktop.
Save evgv/2ba9e494492ff0fba8a143bc969cd06e to your computer and use it in GitHub Desktop.
Regular expressions.

Regular expressions

The list will be supplemented

Cut all from string exept numbers

    $string = 'jkwei fwoewego bo7  hp9gghwhl wekof we90fgweh wempgojwe90';

    echo preg_replace('/[^0-9]/', '', $string); // 799090

Cut all whitespaces from string

  $string = 'Hello World!';

  echo preg_replace('/\s/', '', $string); // HelloWorld!

Validate MAC address

    $pattern = "/(^((([a-f\d]{2}(-|:)){5})|(([a-f\d]{2}-){7}))[a-f\d]{2}$)|(^([a-f\d]{4}.){2}[a-f\d]{4}$)/i";
    
    preg_match($pattern, "0A-53-70-87-10-4F"); // true
    preg_match($pattern, "00-53-70-87-10-4f-4E-4f"); // true
    preg_match($pattern, "00:53:70:87:10:4f"); // true
    preg_match($pattern, "0053.7087.104f"); // true
    
    preg_match($pattern.$flag, "0A-53-70-87-10-4"); // false
    preg_match($pattern, "00-53-70-87-10-4E-4F"); // false
    preg_match($pattern, "00:53:70:87:10"); // false
    preg_match($pattern, "0053.7087.104F.114D"); // false

Validate (GPS cords)

From stack

Latitude

^(\+|-)?(?:90(?:(?:\.0{1,6})?)|(?:[0-9]|[1-8][0-9])(?:(?:\.[0-9]{1,6})?))$
<iframe frameborder="0" width="842" height="282" src="https://jex.im/regulex/#!embed=true&flags=&re=%5E(%5C%2B%7C-)%3F(%3F%3A90(%3F%3A(%3F%3A%5C.0%7B1%2C6%7D)%3F)%7C(%3F%3A%5B0-9%5D%7C%5B1-8%5D%5B0-9%5D)(%3F%3A(%3F%3A%5C.%5B0-9%5D%7B1%2C6%7D)%3F))%24"></iframe>

Longitude

^(\+|-)?(?:180(?:(?:\.0{1,6})?)|(?:[0-9]|[1-9][0-9]|1[0-7][0-9])(?:(?:\.[0-9]{1,6})?))$
<iframe frameborder="0" width="970" height="352" src="https://jex.im/regulex/#!embed=true&flags=&re=%5E(%5C%2B%7C-)%3F(%3F%3A180(%3F%3A(%3F%3A%5C.0%7B1%2C6%7D)%3F)%7C(%3F%3A%5B0-9%5D%7C%5B1-9%5D%5B0-9%5D%7C1%5B0-7%5D%5B0-9%5D)(%3F%3A(%3F%3A%5C.%5B0-9%5D%7B1%2C6%7D)%3F))%24"></iframe>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment