15 Useful PHP Regular expressions

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

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

$url = "http://komunitasweb.com/"if (preg_match$url)) {    Echo "Your URL is ok."  Else  {   echo "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.

$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 re Gexen) is written in a formal language so can be interpreted by a regular expression processor";   $text Preg_replace $text );   Echo $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

Echo $title; now, just before the modified line, add this code: <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;}

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

$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); } } 

Remove duplicate letters

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

$text Preg_replace $text

Remove Duplicate punctuation

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

$text Preg_replace $text

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.

function $tag $xml  $tagpreg_quote($tagpreg_match_all(' {< ').  $tag. ' [^>]*> (. *?) </'. $tag. ' The. '} ' ,           $xml,           $matches,           preg_pattern_order);  

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 value, 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]; } 

Match hexadecimal color values

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

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

Find page Title

This code makes it easy to find and print content between pages <title> and </title>

  $fp  = fopen  ("http/ Www.catswhocode.com/blog "," R ");  while  (! ( $fp    $page . = fgets  ( $fp , 4096);   $titre  = eregi  ("<title> ( . *) </title> ",  $page ,  $regs  );  echo   $regs  [1];  fclose  ( $fp ); 

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?

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?
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 content
Preg_replace $text

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

<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; >

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

$texte= ' A text with a smiley 'echostr_replace(':-) ', ' $texte

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 $str );  

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

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.