15 Practical PHP regular expressions

Source: Internet
Author: User
Tags php regular expression wordpress blog
15 Practical PHP regular expressions are a very useful function for developers. they provide searching, matching, replacing sentences, words, or strings in other formats. This article mainly introduces 15 Super Practical php regular expressions, which can be referenced by friends. In this article, I have compiled 15 extremely useful regular expressions. WEB developers should add them to their toolkit.

Verify the domain name to check 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."; }

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 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";  $text = preg_replace("/b(regex)b/i", '1', $text);  echo $text;

Highlight the query results in your WordPress blog as I said just now. the above code can easily search for results, here is a better way to perform a search to open your file search on a WordPress blog. php, find the method the_title (), and replace it with the following code.

echo $title;   Now, just before the modified line, add this code:   
 
  \0',      $title);  >   Save the search.php file and open style.css. Append the following line to it:   strong.search-excerpt { background: yellow; }
 

Retrieve all images from HTML documents

If you want to get all the images on a webpage, this code is what you need. you can easily create an image download robot.

$images = array(); preg_match_all('/(img|src)=("|')[^"'>]+/i', $data, $media); unset($data); $data=preg_replace('/(img|src)("|'|="|=')(.*)/i',"$3",$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);   } }

Delete duplicate letters

Do I often enter multiple letters? This expression is suitable.

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

Delete duplicate punctuation

Functions are the same as above, but only punctuation marks are repeated.

$text = preg_replace("/.+/i", ".", $text);

Matching an XML or HTML tag

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

function get_tag( $tag, $xml ) { $tag = preg_quote($tag); preg_match_all('{<'.$tag.'[^>]*>(.*?)
 .'}',           $xml,           $matches,           PREG_PATTERN_ORDER);  return $matches[1]; }

Matching XML or HTML tags with attribute values

This function is very similar to the above, but it allows you to match tags with internal attribute values. for example, you can easily match

function get_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]; }

Match hexadecimal color values

Another interesting web developer tool that allows you to match and verify hexadecimal color values.

$string = "#555555"; if (preg_match('/^#(?:(?:[a-fd]{3}){1,2})$/i', $string)) { echo "example 6 successful."; }

Search page title

This code facilitates searching and printing Web pagesAndContent

$fp = fopen("http://www.catswhocode.com/blog","r"); while (!feof($fp) ){   $page .= fgets($fp, 4096); }  $titre = eregi("(.*)",$page,$regs); echo $regs[1]; fclose($fp);

Apache logs

Most websites use the famous Apache server. If your website is the same, what if you use the PHP regular expression 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)[^"]*)"$'

Use smart quotes instead of double quotation marks

If you are a printing enthusiast, you will like this regular expression that allows you to use smart quotes instead of double quotation marks. this regular expression is used by WORDPRESS in its content.

preg_replace('B"b([^"x84x93x94rn]+)b"B', '?1?', $text);

Verify password complexity

This regular expression checks whether the input content contains 6 or more letters, numbers, underscores, and hyphens. the input must contain at least one uppercase letter, one lowercase letter, 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 regular expressions to obtain images on the post.

I know that many people are WORDPRESS users, and you may like and are willing to use the image code retrieved from the content of the post. To use this code in your BLOG, you only need to copy the following code to one of your files.

  
    
   
    post_content; $szSearchPattern = '~]* />~';  // Run preg_match_all to grab all the images and save the results in $aPics preg_match_all( $szSearchPattern, $szPostContent, $aPics );  // Check to see if we have at least 1 image $iNumberOfPics = count($aPics[0]);  if ( $iNumberOfPics > 0 ) {    // Now here you would do whatever you need to do with the images    // For this example the images are just displayed    for ( $i=0; $i < $iNumberOfPics ; $i++ ) {      echo $aPics[0][$i];    }; };  endwhile; endif; >
   
  
 

Automatic smiling face generation

Another method used by WordPress. this code enables you to automatically replace an image with a smiley face.

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

Remove Image link

  
 
  
)/", '$ 2', $ str); echo preg_replace ("/() (<\/a>)/",' \ 2 ', $ str);>
 

The above are 15 Super Practical php regular expressions. I hope they will be helpful for your learning.

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.