溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

15個(gè)實(shí)用的PHP正則表達(dá)式分別是什么

發(fā)布時(shí)間:2021-10-18 17:23:38 來源:億速云 閱讀:142 作者:柒染 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)15個(gè)實(shí)用的PHP正則表達(dá)式分別是什么,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

對(duì)于開發(fā)人員來說,正則表達(dá)式是一個(gè)非常有用的功能,它提供了 查找,匹配,替換  句子,單詞,或者其他格式的字符串。這篇文章主要介紹了15個(gè)超實(shí)用的php正則表達(dá)式,需要的朋友可以參考下。在這篇文章里,我已經(jīng)編寫了15個(gè)超有用 的正則表達(dá)式,WEB開發(fā)人員都應(yīng)該將它收藏到自己的工具包。

15個(gè)實(shí)用的PHP正則表達(dá)式分別是什么

驗(yàn)證域名檢驗(yàn)一個(gè)字符串是否是個(gè)有效域名

$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."; }

從一個(gè)字符串中 突出某個(gè)單詞

這是一個(gè)非常有用的在一個(gè)字符串中匹配出某個(gè)單詞 并且突出它,非常有效的搜索結(jié)果

$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", '<span style="background:#5fc9f6">1</span>', $text);  echo $text;

突出查詢結(jié)果在你的 WordPress  博客里就像剛才我說的,上面的那段代碼可以很方便的搜索出結(jié)果,而這里是一個(gè)更好的方式去執(zhí)行搜索在某個(gè)WordPress的博客上打開你的文件  search.php ,然后找到 方法 the_title() 然后用下面代碼替換掉它

  1. echo $title;  

  2.  

  3. Now, just before the modified line, add this code:  

  4.  

  5. <php  

  6.   $title   = get_the_title();  

  7.   $keys= explode(" ",$s);  

  8.   $title   = preg_replace('/('.implode('|', $keys) .')/iu',  

  9.     '<strong>\0</strong>',  

  10.     $title);  

  11. >  

  12.  

  13. Save the search.php file and open style.css. Append the following line to it:  

  14.  

  15. strong.search-excerpt { background: yellow; }

從HTML文檔中獲得全部圖片

如果你曾經(jīng)希望去獲得某個(gè)網(wǎng)頁上的全部圖片,這段代碼就是你需要的,你可以輕松的建立一個(gè)圖片下載機(jī)器人

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

刪除重復(fù)字母

經(jīng)常重復(fù)輸入字母? 這個(gè)表達(dá)式正適合.

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

刪除重復(fù)的標(biāo)點(diǎn)

功能同上,但只是面對(duì)標(biāo)點(diǎn),白白重復(fù)的逗號(hào)

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

匹配一個(gè)XML或者HTML標(biāo)簽

這個(gè)簡單的函數(shù)有兩個(gè)參數(shù):***個(gè)是你要匹配的標(biāo)簽,第二個(gè)是包含XML或HTML的變量,再強(qiáng)調(diào)下,這個(gè)真的很強(qiáng)大

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

匹配具有屬性值的XML或者HTML標(biāo)簽

這個(gè)功能和上面的非常相似,但是它允許你匹配的標(biāo)簽內(nèi)部有屬性值,例如你可以輕松匹配 <div id=”header”>

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

匹配十六進(jìn)制顏色值

web開發(fā)者的另一個(gè)有趣的工具,它允許你匹配和驗(yàn)證十六進(jìn)制顏色值.

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

查找頁面 title

這段代碼方便查找和打印 網(wǎng)頁 <title> 和</title> 之間的內(nèi)容

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

解釋 Apache 日志

大多數(shù)網(wǎng)站使用的都是著名的Apache服務(wù)器,如果你的網(wǎng)站也是,那么使用PHP正則表達(dá)式解析 apache 服務(wù)器日志 怎么樣?

//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)[^"]*)"$'

使用智能引號(hào)代替雙引號(hào)

如果你是一個(gè)印刷愛好者,你將喜歡這個(gè)允許用智能引號(hào)代替雙引號(hào)的正則表達(dá)式,這個(gè)正則被WORDPRESS在其內(nèi)容上使用

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

檢驗(yàn)密碼的復(fù)雜度

這個(gè)正則表達(dá)式將檢測(cè)輸入的內(nèi)容是否包含6個(gè)或更多字母,數(shù)字,下劃線和連字符. 輸入必須包含至少一個(gè)大寫字母,一個(gè)小寫字母和一個(gè)數(shù)字

'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: 使用正則獲得帖子上的圖片

我知道很多人是WORDPRESS的使用者,你可能會(huì)喜歡并且愿意使用 那些從帖子的內(nèi)容檢索下來的圖像代碼。使用這個(gè)代碼在你的BLOG只需要復(fù)制下面代碼到你的某個(gè)文件里

<php if (have_posts()) : ?> <php while (have_posts()) : the_post(); ?>  <php $szPostContent = $post->post_content; $szSearchPattern = '~<img [^>]* />~';  // 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; >

自動(dòng)生成笑臉圖案

被WordPress使用的另一個(gè)方法, 這段代碼可使你把圖像自動(dòng)更換一個(gè)笑臉符號(hào)

$texte='A text with a smiley '; echo str_replace(':-)','<img src="smileys/souriant.png">',$texte);

移除圖片的鏈接

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <php   $str = '     <a href="http://www.jobbole.com/">jobbole</a>其他字符     <a href="http://www.sohu.com/">sohu</a>     <a href="http://www.sohu.com/"><img src="http://www.fashion-press.net/img/news/3176/mot_06.jpg" /></a>     <br>';    //echo preg_replace("/(<a.*?>)(<img.*?>)(<\/a>)/", '$2', $str);    echo preg_replace("/(<a.*?>)(<img.*?>)(<\/a>)/", '\2', $str);  >

關(guān)于15個(gè)實(shí)用的PHP正則表達(dá)式分別是什么就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI