設為首頁收藏本站

艾歐踢論壇

 找回密碼
 立即註冊

QQ登錄

只需一步,快速開始

搜索
熱搜: 活動 交友 discuz
查看: 731|回復: 0
打印 上一主題 下一主題

PHP 新手工程師的百寶袋:15 個食用之萬用正規表示式

[複製鏈接]
跳轉到指定樓層
樓主
發表於 2016-1-17 10:44:55 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
  • 驗證域名檢驗一個字符串是否是個有效域名
  1. $url = "http://komunitasweb.com/";
  2. if (preg_match('/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i', $url)) {
  3.   echo "Your url is ok.";
  4. } else {
  5.   echo "Wrong url.";
  6. }
複製代碼

  • 從一個字符串中突出某個單詞
這是一個非常有用的在一個字符串中匹配出某個單詞並且突出它,非常有效的搜索結果
  1. $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
  2. regexp, with plural forms regexes, regexps, or regexen) are written in a formal language that can be interpreted by a regular expression processor";
  3. $text = preg_replace("/b(regex)b/i", '<span style="background:#5fc9f6">1</span>', $text);
  4. echo $text;
複製代碼

突出查詢結果在你的 WordPress 部落格裡就像剛才我說的,上面的那段代碼可以很方便的搜索出結果,而這裡是一個更好的方式去執行搜索在某個 WordPress 上打開你的文件 search.php ,然後找到方法 the_title() 然後用下面代碼替換掉它
  1. echo $title;

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

  3. <?php
  4.   $title   = get_the_title();
  5.   $keys= explode(" ",$s);
  6.   $title   = preg_replace('/('.implode('|', $keys) .')/iu',
  7.     '<strong>\0</strong>',
  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; }
複製代碼


  • 從 HTML 文檔中獲得全部圖片
如果你曾經希望去獲得某個網頁上的全部圖片,這段代碼就是你需要的,你可以輕鬆的建立一個圖片下載機器人
  1. $images = array();
  2. preg_match_all('/(img|src)=("|')[^"'>]+/i', $data, $media);
  3. unset($data);
  4. $data=preg_replace('/(img|src)("|'|="|=')(.*)/i',"$3",$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. }
複製代碼


  • 刪除重複字母
經常重複輸入字母? 這個正適合
  1. $text = preg_replace("/s(w+s)1/i", "$1", $text);
複製代碼


  • 刪除重複的標點
功能同上,但只是面對標點,白白重複的逗號
  1. $text = preg_replace("/.+/i", ".", $text);
複製代碼


  • 匹配一個 XML 或者 HTML 標籤
這個簡單的函數有兩個參數:第一個是你要匹配的標籤,第二個是包含 XML 或 HTML 的變量,再強調下,這個真的很強大
  1. function get_tag( $tag, $xml ) {
  2. $tag = preg_quote($tag);
  3. preg_match_all('{<'.$tag.'[^>]*>(.*?)</'.$tag.'>.'}',
  4.           $xml,
  5.           $matches,
  6.           PREG_PATTERN_ORDER);

  7. return $matches[1];
  8. }
複製代碼

  • 匹配具有屬性值的 XML 或者 HTML 標籤
這個功能和上面的非常相似,但是它允許你匹配的標籤內部有屬性值,例如你可以輕鬆匹配<div id=”header”>
  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. }
複製代碼


  • 匹配十六進制顏色值
web 開發者的另一個有趣的工具,它允許你匹配和驗證十六進制顏色值
  1. $string = "#555555";
  2. if (preg_match('/^#(?:(?:[a-fd]{3}){1,2})$/i', $string)) {
  3. echo "example 6 successful.";
  4. }
複製代碼


  • 查找頁面 title
這段代碼方便查找和打印網頁<title> 和</title> 之間的內容
  1. $fp = fopen("http://www.catswhocode.com/blog","r");
  2. while (!feof($fp) ){
  3.   $page .= fgets($fp, 4096);
  4. }

  5. $titre = eregi("<title>(.*)</title>",$page,$regs);
  6. echo $regs[1];
  7. fclose($fp);
複製代碼


  • 解釋 Apache 日誌
大多數網站使用的都是著名的 Apache 服務器,如果你的網站也是,那麼使用 PHP 正則表達式解析 apache 服務器日誌怎麼樣?
  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. [list]
  5. [*]使用智慧引號代替雙引號
  6. [/list]如果你是一個印刷愛好者,你將喜歡這個允許用智慧引號代替雙引號的正規表示式,這個正則被 WORDPRESS 在其內容上使用
  7. [code]preg_replace('B"b([^"x84x93x94rn]+)b"B', '?1?', $text);
複製代碼


  • 檢驗密碼的複雜度
這個正則表達式將檢測輸入的內容是否包含 6 個或更多字母,數字,下劃線和連字符. 輸入必須包含至少一個大寫字母,一個小寫字母和一個數字
  1. '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 的使用者,你可能會喜歡並且願意使用那些從帖子的內容檢索下來的圖像代碼。使用這個代碼在你的 BLOG 只需要復制下面代碼到你的某個文件裡
  1. <?php if (have_posts()) : ?>
  2. <?php while (have_posts()) : the_post(); ?>

  3. <?php
  4. $szPostContent = $post->post_content;
  5. $szSearchPattern = '~<img [^>]* />~';

  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 have at least 1 image
  9. $iNumberOfPics = count($aPics[0]);

  10. if ( $iNumberOfPics > 0 ) {
  11.    // Now here you would do whatever you need to do with the images
  12.    // For this example the images are just displayed
  13.    for ( $i=0; $i < $iNumberOfPics ; $i++ ) {
  14.      echo $aPics[0][$i];
  15.    };
  16. };

  17. endwhile;
  18. endif;
  19. ?>
複製代碼


  • 自動生成笑臉圖案
被 WordPress 使用的另一個方法, 這段代碼可使你把圖像自動更換一個笑臉符號
  1. $texte='A text with a smiley ';
  2. echo str_replace(':-)','<img src="smileys/souriant.png">',$texte);
複製代碼

  • 移除圖片的鏈接
    1. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    2. <?php
    3.   $str = '
    4.     <a href="http://www.jobbole.com/">jobbole</a>其他字符
    5.     <a href="http://www.sohu.com/">sohu</a>
    6.     <a href="http://www.sohu.com/"><img src="http://www.fashion-press.net/img/news/3176/mot_06.jpg" /></a>
    7.     <br>';

    8.   //echo preg_replace("/(<a.*?>)(<img.*?>)(<\/a>)/", '$2', $str);  
    9.   echo preg_replace("/(<a.*?>)(<img.*?>)(<\/a>)/", '\2', $str);  
    10. ?>
    複製代碼





分享到:  QQ好友和群QQ好友和群 QQ空間QQ空間 騰訊微博騰訊微博 騰訊朋友騰訊朋友
收藏收藏 轉播轉播 分享分享 分享淘帖
回復

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即註冊

本版積分規則

小黑屋|Archiver|手機版|艾歐踢創新工坊    

GMT+8, 2024-5-16 01:19 , Processed in 0.232395 second(s), 21 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表