15 Useful PHP Regular expressions

Source: Internet
Author: User
Tags uppercase letter wordpress blog

Article from: http://mp.weixin.qq.com/s?__biz=MzI0MjEwMDMzNQ==&mid=402026190&idx=1&sn= Ee4c99319335e150b2b673208a5c78eb&scene=23&srcid=1214pt4mvoa8gjqh8mgwbsmp#rd

This article reads quickly:

1. Verify that the domain name verifies whether a string is a valid domain name

2. Highlight a word from a string

3. Get all the pictures from the HTML document

4. Delete duplicate Letters

5. Remove duplicate punctuation

6. Match an XML or HTML tag

7. Match XML or HTML tags with attribute values

8. Matching hexadecimal color values

9. Find Page Title

10. Interpreting Apache Logs

11. Use smart quotes instead of double quotes

12. Verify the complexity of the password

WordPress: Use the regular to get the picture on the post

14. Automatically create a smiley face pattern

15. Remove a link to a picture

For developers, regular expressions are a useful feature that provides strings for finding, matching, replacing sentences, words, or other formats. This article mainly introduces 15 super-practical PHP regular expressions, the need for friends can refer to. In this article, I've written 15 super-useful regular expressions that Web developers should be able to bookmark in their own toolkits.

1.Verify that the domain name verifies whether a string is a valid domain name$url= "http://komunitasweb.com/"; if(Preg_match('/^ (HTTP|HTTPS|FTP)://([A-z0-9][a-z0-9_-]* (?:..) [ a-z0-9][a-z0-9_-]*) +):? (d+)?/?/i ',$url)) {   Echo"Your URL is ok."; } Else {   Echo"Wrong URL."; }2.To highlight a word from a string this is a very useful search result that matches a word in a string and highlights it .$text= "Sample sentence from Komunitasweb, regex have 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 Regexe N) is written in a formal language so can be interpreted by a regular expression processor"; $text=Preg_replace("/b (Regex) b/i", ' <span style= "background: #5fc9f6" >1</span> ",$text); Echo $text; Highlight query results in your WordPress blog as I said earlier, the above code can be very convenient to search for results, and here is a better way to perform a search on a wordpress blog to open your file search.PHP, then find the method The_title () and replace it with the following codeEcho $title; now, just before the modified line, add this code: &LT;?PHP$title=Get_the_title (); $keys=Explode(" ",$s); $title=Preg_replace(‘/(‘.implode(' | ',$keys) .‘) /iu ', ' <strong>\0</strong> ',$title); ?>Save the search. phpfileand open style.css. Append the following line to it:Strong. search-excerpt {background:Yellow;}3.get all the pictures from an HTML document if you ever want to get all the pictures on a webpage, this code is what you need, you can easily build a picture to download the robot$images=Array(); Preg_match_all('/(IMG|SRC) = ("| ') [^ "' >]+/i ',$data,$media); Unset ($data); $data=preg_replace ('/(IMG|SRC) (' | ' | = "|=") (. *)/I ', "$ $", $media [0]);   foreach ($data as $url) {$info = PathInfo ($url); if (Isset ($info [' Extension ']) {if ($info [' extension '] = = ' jpg ') || ($info [' extension '] = = ' jpeg ') || ($info [' extension '] = = ' gif ') || ($info [' extension '] = = ' png ') ) Array_push ($images, $url); }}4. Delete duplicate letters often repeat the letter entered? This expression is just right for. $text = Preg_replace ("/s (w+s) 1/i", "$", $text); 5. Remove duplicate punctuation function as above, but only face punctuation, white repeating comma $text = preg_replace ("/.+/i", ".", $text); 6. A simple function that matches an XML or HTML tag has two parameters: the first is the tag you want to match, the second is a variable containing XML or HTML, and again, this is really powerful function get_tag ($tag, $xml) {$tag = Preg_  Quote ($TAG); Preg_match_all (' {< '. $tag. ' [^>]*> (. *?) </'. $tag. ' . '} ',$xml,$matches,Preg_pattern_order); return $matches[1]; }7.matching an XML or HTML tag with an attribute value is very similar to the above, but it allows you to match a tag with a property value inside it, for example, you can easily match<div id= "Header">functionGet_tag ($attr,$value,$xml,$tag=NULL ) {  if(Is_null($tag) )   $tag= ' \w+ '; Else   $tag=Preg_quote($tag); $attr=Preg_quote($attr); $value=Preg_quote($value); $tag _regex= "/< (".$tag.") [^>]*$attr\s*=\s* ". "([‘\"])$value\\2[^>]*> (. *?) <\/\\1>/"Preg_match_all($tag _regex,$xml,$matches,Preg_pattern_order); return $matches[3]; }8.Match hex Color value Another interesting tool for Web developers that allows you to match and validate hexadecimal color values.$string= "#555555"; if(Preg_match('/^# (?:(?: [A-fd]{3}) {$/i}) ',$string)) { Echo"Example 6 successful."; }9.Find page Title This code makes it easy to find and print Web pages<title> and </title>the content between$fp=fopen("Http://www.catswhocode.com/blog", "R");  while(!feof($fp) ){   $page.=fgets($fp, 4096); } $titre=Eregi("<title> (. *) </title>",$page,$regs); Echo $regs[1]; fclose($fp);10.explain Apache logs most websites use the famous Apache server, and if your site is also, how about using PHP regular expressions to parse Apache server logs? //logs:apache Web server//successful hits to HTML files only. Useful for counting the number of page views. ' ^ ((? #client IP or domain name) s+) s+ ((? #basic authentication) s+s+s+) s+[((? #date and time) [^]]+]]s+ "(?: get| Post| HEAD) ((? #file)/[^? "] +?. html?)?? ((? #parameters) [^? "] +)? Http/[0-9.] + "s+ (? #status code) 200s+ ((? #bytes transferred) [ -0-9]+] s+" ((? #referrer) [^ "]*]" s+ "((? #user agent) [^"]*) "$ '//logs:apache Web server//404 errors only' ^ ((? #client IP or domain name) s+) s+ ((? #basic authentication) s+s+s+) s+[((? #date and time) [^]]+]]s+ "(?: get| Post| HEAD) ((? #file) [^? "] +)?? ((? #parameters) [^? "] +)? Http/[0-9.] + "s+ (? #status code) 404s+ ((? #bytes transferred) [ -0-9]+] s+" ((? #referrer) [^ "]*]" s+ "((? #user agent) [^"]*) "$ ' 11.Use smart quotes instead of double quotes if you're a print enthusiast, you'll like this regular expression that allows smart quotes instead of double quotes, which is used by WordPress on its contentPreg_replace(' B ' B ([^ ' x84x93x94rn]+] B "B ', '? 1? '),$text);12.Verify the complexity of the password this regular expression will detect if the input contains 6 or more letters, numbers, underscores, and hyphens.the input must contain at least one uppercase letter, one lowercase letters, and one number' A (? =[-_a-za-z0-9]*?[ A-z]) (? =[-_a-za-z0-9]*?[ A-z]) (? =[-_a-za-z0-9]*?[ 0-9]) [-_a-za-z0-9]{6,}z ' 13. Wordpress:use regular to get pictures on posts I know a lot of people are WordPress users, and you might like and want to use the image code retrieved from the content of the post. Use this code in your blog only need to copy the following code into one of your files<?phpif(Have_posts ()):?> <?php while(Have_posts ()): The_post ();?> <?PHP$szPostContent=$post-post_content;$szSearchPattern= ' ~]*/>~ '; //Run Preg_match_all to grab all the images and save the results in $aPicsPreg_match_all($szSearchPattern,$szPostContent,$aPics ); //Check to see if we had at least 1 image$iNumberOfPics=Count($aPics[0]); if($iNumberOfPics> 0 ) {    //Now here you would does whatever you need to does with the images//For this example the images is just displayed 
        for($i= 0;$i<$iNumberOfPics;$i++ ) {      Echo $aPics[0] [$i]; }; }; Endwhile; endif; ? >14.another way to automatically generate a smiley face pattern used by WordPress,This code allows you to automatically replace the image with a smiley face symbol$texte= ' A text with a smiley '; Echo Str_replace(':-) ', '  ',$texte);15.remove a link from a picture<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/> <?PHP$str=<a href= "http://www.jobbole.com/" >jobbole</a> other characters <a href= "http://www.sohu.com/" >sohu</a > <a href= "http://www.sohu.com/" ></a> <br>‘; //echo Preg_replace ("/(<a.*?>) () (<\/a>)/", ' $ $ ', $str);   Echo Preg_replace("/(<a.*?>) () (<\/a>)/", ' \2 ',$str); ?>

15 Useful PHP Regular expressions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.