Posted By

fackz on 04/20/09


Tagged

regex functions validation


Versions (?)


Advertising

Website Promotion DIRECTORY is a crucial factor for all websites that need to gain better organic search engine rankings and increase website traffic.
Submitting your website as part of your Web Promotion strategy to our SEO friendly and high traffic Business Directory for review is an excellent way to gain a valuable backlink and increase your websites visibility online.

Submit Site


Who likes this?

3 people have marked this snippet as a favorite

fackz
atma
vali29


Useful regex functions


Published in: PHP 






Expand | Embed | Plain Text
  1. <?php
  2.  
  3. //Some regex functions:
  4.  
  5. //A better solution for validate email syntax is using filter_var.
  6. if (filter_var('test+email@fexample.com', FILTER_VALIDATE_EMAIL)) {
  7. echo "Your email is ok.";
  8. } else {
  9. echo "Wrong email address format.";
  10. }
  11.  
  12.  
  13.  
  14. //Validate username, consist of alpha-numeric (a-z, A-Z, 0-9), underscores, and has minimum 5 character and maximum 20 character.
  15. //You could change the minimum character and maximum character to any number you like.
  16. $username = "user_name12";
  17. if (preg_match('/^[a-z\d_]{5,20}$/i', $username)) {
  18. echo "Your username is ok.";
  19. } else {
  20. echo "Wrong username format.";
  21. }
  22.  
  23. //Validate domain
  24. $url = "http://komunitasweb.com/";
  25. if (preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) {
  26. echo "Your url is ok.";
  27. } else {
  28. echo "Wrong url.";
  29. }
  30.  
  31.  
  32. //Extract domain name from certain URL
  33. $url = "http://komunitasweb.com/index.html";
  34. preg_match('@^(?:http://)?([^/]+)@i', $url, $matches);
  35. $host = $matches[1];
  36. echo $host;
  37.  
  38.  
  39. //Highlight a word in the content
  40. $text = "Sample sentence from KomunitasWeb, regex has become popular in web programming. Now we learn regex. According to wikipedia, Regular expressions (abbreviated as regex or regexp, with plural forms regexes, regexps, or regexen) are written in a formal language that can be interpreted by a regular expression processor";
  41. $text = preg_replace("/\b(regex)\b/i", '<span style="background:#5fc9f6">\1</span>', $text);
  42. echo $text;
  43.  
  44.  
  45.  
  46.  
  47.  
  48. ?>

Report this snippet 

You need to login to post a comment.