admin 發表於 2016-1-17 10:44:55

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


[*]驗證域名檢驗一個字符串是否是個有效域名
$url = "http://komunitasweb.com/";
if (preg_match('/^(http|https|ftp)://(*(?:.*)+):?(d+)?/?/i', $url)) {
echo "Your url is ok.";
} else {
echo "Wrong url.";
}


[*]從一個字符串中突出某個單詞
這是一個非常有用的在一個字符串中匹配出某個單詞並且突出它,非常有效的搜索結果
$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;
突出查詢結果在你的 WordPress 部落格裡就像剛才我說的,上面的那段代碼可以很方便的搜索出結果,而這裡是一個更好的方式去執行搜索在某個 WordPress 上打開你的文件 search.php ,然後找到方法 the_title() 然後用下面代碼替換掉它
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; }


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


[*]刪除重複字母
經常重複輸入字母? 這個正適合
$text = preg_replace("/s(w+s)1/i", "$1", $text);


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


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

return $matches;
}


[*]匹配具有屬性值的 XML 或者 HTML 標籤
這個功能和上面的非常相似,但是它允許你匹配的標籤內部有屬性值,例如你可以輕鬆匹配<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;
}


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


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

$titre = eregi("<title>(.*)</title>",$page,$regs);
echo $regs;
fclose($fp);


[*]解釋 Apache 日誌
大多數網站使用的都是著名的 Apache 服務器,如果你的網站也是,那麼使用 PHP 正則表達式解析 apache 服務器日誌怎麼樣?
//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/+"s+(?#status code)200s+((?#bytes transferred)[-0-9]+)s+"((?#referrer)[^"]*)"s+"((?#user agent)[^"]*)"


[*]使用智慧引號代替雙引號
如果你是一個印刷愛好者,你將喜歡這個允許用智慧引號代替雙引號的正規表示式,這個正則被 WORDPRESS 在其內容上使用
preg_replace('B"b([^"x84x93x94rn]+)b"B', '?1?', $text);


[*]檢驗密碼的複雜度
這個正則表達式將檢測輸入的內容是否包含 6 個或更多字母,數字,下劃線和連字符. 輸入必須包含至少一個大寫字母,一個小寫字母和一個數字
'A(?=[-_a-zA-Z0-9]*?)(?=[-_a-zA-Z0-9]*?)(?=[-_a-zA-Z0-9]*?)[-_a-zA-Z0-9]{6,}z'


[*]WordPress: 使用正則獲得帖子上的圖片
我知道很多人是 WORDPRESS 的使用者,你可能會喜歡並且願意使用那些從帖子的內容檢索下來的圖像代碼。使用這個代碼在你的 BLOG 只需要復制下面代碼到你的某個文件裡
<?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);

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[$i];
   };
};

endwhile;
endif;
?>


[*]自動生成笑臉圖案
被 WordPress 使用的另一個方法, 這段代碼可使你把圖像自動更換一個笑臉符號
$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);
?>




頁: [1]
查看完整版本: PHP 新手工程師的百寶袋:15 個食用之萬用正規表示式