15 useful PHP Regular Expressions _php Tutorials

Source: Internet
Author: User
Tags php regular expression uppercase letter wordpress blog

15 Useful PHP Regular expressions


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.

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

 
  
  
  1. "http://komunitasweb.com/"
  2. if (Preg_match ('/^ (HTTP|HTTPS|FTP)://([A-z0-9][a-z0-9_-]* (?:.. [ a-z0-9][a-z0-9_-]*) +):? (d+)?/?/i '
  3. "Your URL is ok."
  4. Else
  5. "Wrong URL."

To highlight a word from a string

This is a very useful search result that matches a word in a string and highlights it.

 
  
  
  1. $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
  2. RegExp, with plural forms regexes, regexps, or Regexen) is written in a formal language so can be interpreted by a Regu Lar expression Processor ";
  3. $text = Preg_replace ("/b (Regex) b/i"'1', $text) ;

Highlight query results in your WordPress blog as I said earlier, the above code can be very convenient to search results, and here is a better way to perform a search on a wordpress blog open your file search.php, and then find the method the_ Title () and replace it with the following code

 
 
  1. echo $title;
  2. Now, just before the modified line, add this code:
  3. < span="">
  4. $title = Get_the_title ();
  5. $keys = Explode ("", $s);
  6. $title = preg_replace ('/('. Implode ('| ') , $keys). ')/iu ',
  7. '+ ' ,
  8. $title);
  9. >
  10. Save the search.php file and open style.css. Append the following line to it:
  11. strong.search-excerpt {background:yellow;}

Get all the pictures from the 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

 
 
  1. $images = Array ();
  2. Preg_match_all ('/(IMG|SRC) = (' | ') ) [^ "' >]+/i ', $data, $media);
  3. Unset ($data);
  4. $data =preg_replace ('/(IMG|SRC) (' | ') |="|= ') (. *)/I ',"$ $", $media [0]);
  5. foreach ($data as $url)
  6. {
  7. $info = PathInfo ($url);
  8. if (Isset ($info [' extension ')])
  9. {
  10. if ($info [' extension '] = = ' jpg ') | |
  11. ($info [' extension '] = = ' jpeg ') | |
  12. ($info [' extension '] = = ' gif ') | |
  13. ($info [' extension '] = = ' png '))
  14. Array_push ($images, $url);
  15. }
  16. }

Remove duplicate letters

Do you always enter letters repeatedly? This expression is suitable.

 
  
  
  1. $text = preg_replace ("/s (w+s) 1/i"" $"

Remove Duplicate punctuation

function as above, but only face punctuation, white repeating comma

 
  
  
  1. $text = preg_replace ("/.+/i""." )

Match an XML or HTML tag

This simple function has two parameters: the first is the tag you want to match, the second is a variable that contains XML or HTML, and again, this is really powerful.

 
  
  
  1. Preg_match_all (' {< '. $tag. ' [^>]*> (. *?) . $tag. '. '
  2. return $matches [1

Match XML or HTML tags that have attribute values

This feature is very similar to the above, but it allows you to match the inside of the tag with the attribute values, for example you can easily match

 
 
  1. function Get_tag ($attr, $value, $xml, $tag =null ) {
  2. if (Is_null ($tag))
  3. $tag = ' \w+ ';
  4. Else
  5. $tag = Preg_quote ($tag);
  6. $attr = Preg_quote ($attr);
  7. $value = Preg_quote ($value);
  8. $tag _regex = "/< (". $tag. ") [^>]* $attr \s*=\s*. ]
  9. "([' \"]) $value \\2[^>]*> (. *?) <\/\\1>/"
  10. Preg_match_all ($tag _regex,
  11. $xml,
  12. $matches,
  13. Preg_pattern_order);
  14. return $matches [3];
  15. }

Match hexadecimal color values

Another interesting tool for Web developers, which allows you to match and validate hexadecimal color values.

 
  
  
  1. "#555555"
  2. if (Preg_match ('/^# (?:(?: [A-fd]{3}) {) $/i '
  3. "Example 6 successful."

Find page Title

This code makes it easy to find and print Web pagesAndThe content between

 
  
  
  1. $fp = fopen ("Http://www.catswhocode.com/blog","R"
  2. While
  3. 4096
  4. $titre = eregi ("(.*)"
  5. Echo $regs [1

Interpreting Apache Logs

Most websites use the famous Apache server, and if your website is also, how about using PHP regular expressions to parse Apache server logs?

 
 
  1. //logs:apache Web Server
  2. //successful hits to HTML files only. Useful for counting the number of page views.
  3. ' ^ ((? #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) [^"]*) "$ '
  4. //logs:apache Web Server
  5. //404 Errors only
  6. ' ^ ((? #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) [^"]*) "$ '

Use smart quotes instead of double quotes

If you're a print enthusiast, you'll love this regular expression that allows smart quotes instead of double quotes, which is used by WordPress on its content

 
  
  
  1. preg_replace (' B ' B ([^ x84x93x94rn]+) b "b"'? 1? '

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 '

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

I know a lot of people are WordPress users, you might like it 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

 
 
  1. < span=""> if (Have_posts ()):?>
  2. while (Have_posts ()): The_post ();?>
  3. < span="">
  4. $szPostContent = $post->post_content;
  5. $szSearchPattern = ' ~]*/>~ ';
  6. //Run Preg_match_all to grab all the images and save the results in $aPics
  7. Preg_match_all ($szSearchPattern, $szPostContent, $aPics);
  8. //Check to see if we had at least 1 image
  9. $iNumberOfPics = count ($aPics [0]);
  10. if ($iNumberOfPics > 0 ) {
  11. // Now here you would does whatever you need to does with the images
  12. //For this example the images is just displayed
  13. for ($i =0; $i < $iNumberOfPics; $i + +) {
  14. echo $aPics [0] [$i];
  15. };
  16. };
  17. Endwhile;
  18. endif
  19. >

Automatically generate a smiley face pattern

Another method used by WordPress, this code allows you to automatically change the image of a smiley face symbol

 
  
  
  1. $texte = ' A text with a smiley '
  2. echo str_replace (':-) ','

Remove a link from a picture

 
 
  1. "Content-type" content= "text/html; Charset=utf-8 " />
  2. < span="">
  3. $str = '
  4. "http://www.jobbole.com/" >jobbole Other characters
  5. "http://www.sohu.com/" >sohu
  6. "http://www.sohu.com/" >"http://www.fashion-press.net/img/news/3176/mot_06.jpg" />

  7. ';
  8. //echo Preg_replace ("/() () (<\/a>)/", ' $ ", $str);
  9. Echo preg_replace ("/() () (<\/a>)/", ' \2 ', $str);
  10. >

The above is the 15 super-practical PHP regular expression, hope that everyone's learning is helpful.

http://www.bkjia.com/PHPjc/1078009.html www.bkjia.com true http://www.bkjia.com/PHPjc/1078009.html techarticle 15 useful PHP Regular expressions for developers, regular expressions are a very useful feature that provides the ability to find, match, replace sentences, words, or other grids ...

  • 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.