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.
1, verify that the domain name checks whether a string is a valid domain name.
$url = "http://baidu.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. 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 website, 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 that can is 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 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.php file and open style.css. Append the following line to It:strong.search-excerpt {background:yellow;}
3. 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); } }
4. Delete duplicate Letters
Do you always enter letters repeatedly? This expression is suitable.
$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. 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 Get_tag ($tag, $xml) { $tag = Preg_quote ($tag); Preg_match_all (' {< '. $tag. ' [^>]*> (. *?) </'. $tag. ' $xml, $matches, preg_pattern_order); return $matches [1]; }
7. Match XML or HTML tags with 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
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]; }
8. Match Hex color value
Another interesting tool for Web developers, which allows you to match and validate hexadecimal color values.
$string = "#555555"; if (Preg_match (?:(?: [A-fd]{3}) {/^#}) {echo "Example 6 successful.")
9. Find Page Title
This code makes it easy to find and print content between Web pages and
$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. 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?
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 Ti ME) [^]]+]]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 love this regular expression that allows smart quotes instead of double quotes, which is used by WordPress on its content
Preg_replace (' B ' B ([^ ' x84x93x94rn]+) b ' B ', '? 1? ', $text);
12, the complexity of the test 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 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
<?php if (have_posts ()):?> <?php while (Have_posts ()): The_post ();?> <?php $szPostContent = $post->p Ost_content; $szSearchPattern = ' ~]*/>~ '; Run Preg_match_all to grab all the images and save the results in $aPics preg_match_all ($szSearchPattern, $szPostConte NT, $aPics); Check to see if we had at least 1 image $iNumberOfPics = count ($aPics [0]); if ($iNumberOfPics > 0) {//now-here's would do whatever-need to does with the images/for this Exampl E The images is just displayed for ($i =0; $i < $iNumberOfPics; $i + +) { echo $aPics [0][$i];}; Endwhi Le endif;?>
14. Automatically generate 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 '; echo str_replace (':-) ', ' ', $texte);
15, remove the link to the picture
Do you always enter letters repeatedly? This expression is suitable.
<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); >
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.
1, verify that the domain name checks whether a string is a valid domain name.
$url = "http://baidu.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. 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 website, 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 that can is 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 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.php file and open style.css. Append the following line to It:strong.search-excerpt {background:yellow;}
3. 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); } }
4. Delete duplicate Letters
Do you always enter letters repeatedly? This expression is suitable.
$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. 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 Get_tag ($tag, $xml) { $tag = Preg_quote ($tag); Preg_match_all (' {< '. $tag. ' [^>]*> (. *?) </'. $tag. ' $xml, $matches, preg_pattern_order); return $matches [1]; }
7. Match XML or HTML tags with 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
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]; }
8. Match Hex color value
Another interesting tool for Web developers, which allows you to match and validate hexadecimal color values.
$string = "#555555"; if (Preg_match (?:(?: [A-fd]{3}) {/^#}) {echo "Example 6 successful.")
9. Find Page Title
This code makes it easy to find and print content between Web pages and
$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. 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?
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 Ti ME) [^]]+]]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 love this regular expression that allows smart quotes instead of double quotes, which is used by WordPress on its content
Preg_replace (' B ' B ([^ ' x84x93x94rn]+) b ' B ', '? 1? ', $text);
12, the complexity of the test 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 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
<?php if (have_posts ()):?> <?php while (Have_posts ()): The_post ();?> <?php $szPostContent = $post->p Ost_content; $szSearchPattern = ' ~]*/>~ '; Run Preg_match_all to grab all the images and save the results in $aPics preg_match_all ($szSearchPattern, $szPostConte NT, $aPics); Check to see if we had at least 1 image $iNumberOfPics = count ($aPics [0]); if ($iNumberOfPics > 0) {//now-here's would do whatever-need to does with the images/for this Exampl E The images is just displayed for ($i =0; $i < $iNumberOfPics; $i + +) { echo $aPics [0][$i];}; Endwhi Le endif;?>
14. Automatically generate 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 '; echo str_replace (':-) ', ' ', $texte);
15, remove the link to the picture
Do you always enter letters repeatedly? This expression is suitable.
<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); >