有用的正则表达式函数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了有用的正则表达式函数相关的知识,希望对你有一定的参考价值。

  1. <?php
  2.  
  3. //Some regex functions:
  4.  
  5. //A better solution for validate email syntax is using filter_var.
  6. if (filter_var('[email protected]', 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-zd_]{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("/(regex)/i", '<span style="background:#5fc9f6">1</span>', $text);
  42. echo $text;
  43.  
  44.  
  45.  
  46.  
  47.  
  48. ?>

以上是关于有用的正则表达式函数的主要内容,如果未能解决你的问题,请参考以下文章

珍藏版长文详解python正则表达式

正则表达式的有用资源介绍

正则表达式总结及一些有用的例子

20个有用正则表达式

20个有用的正则表达式

text 有用的正则表达式