php中preg_replace和str_replace函數用法

來源:互聯網
上載者:User

str_replace可尋找替換常規字元,
preg_replace可尋找替換斷行符號換行字元(\r\n)
preg_replace常用在

 代碼如下 複製代碼


<meta name="description" content="<?php echo htmlspecialchars(utf_substr(preg_replace('/\r\n/','',str_replace(' ','',strip_tags($this->getDescription()))),400)) ?>">

內容的過濾,過濾斷行符號換行(\r\n)等

 代碼如下 複製代碼

<a href="/%E5%8A%A8%E4%BD%9C%E5%86%92%E9%99%A9_1.html1">首頁</a> <a href="/%E5%8A%A8%E4%BD%9C%E5%86%92%E9%99%A9_1.html0" class="a1">上一頁</a>

用str_replace函數和preg_replace函數替換成

 代碼如下 複製代碼

<a href="/%E5%8A%A8%E4%BD%9C%E5%86%92%E9%99%A9_1.html">首頁</a> <a href="/%E5%8A%A8%E4%BD%9C%E5%86%92%E9%99%A9_1.html" class="a1">上一頁</a>

例子

 代碼如下 複製代碼

$pages = $keyword_data_db->pages;
$pages = str_replace('?page=', '', $pages);
$pages = preg_replace('/_([0-9]+).html([0-9]+)/', '_$2.html', $pages);
$pages = str_replace('_0.html', '_1.html', $pages);

再看個比較例子

 代碼如下 複製代碼


$str =
'111111110000000000000000000000000000000111000001000100010000010010000010010000010100000010
';
$str = str_repeat($str, 1);
$pattern1 = array('12345'=>'', '67891'=>'');
$pattern2 = array('a'=>'', '1234567890'=>'');
$pattern3 = '/12345|67891/';
$pattern4 = '/a|1234567890/';
$pattern5 = array('12345', '67891');
$pattern6 = array('a', '1234567890'); 
$t = microtime(true);

echo microtime(true)-$t, "/n";        //0.4768660068512    2.7257590293884  
$t = microtime(true);
for($i=0; $i<10000; $i++)
{
     preg_replace($pattern3, '', $str);
}
echo microtime(true)-$t, "/n";        //0.30504012107849    1.0864448547363 
$t = microtime(true);
for($i=0; $i<10000; $i++)
{
     preg_replace($pattern4, '', $str);
}
echo microtime(true)-$t, "/n";        //0.30298089981079    1.117014169693  
$t = microtime(true);
for($i=0; $i<10000; $i++)
{
     str_replace($pattern5, '', $str);
}
echo microtime(true)-$t, "/n";        //0.18029189109802    0.22510504722595 
$t = microtime(true);
for($i=0; $i<10000; $i++)
{
     str_replace($pattern6, '', $str);
}
echo microtime(true)-$t, "/n";        //0.18104100227356   0.23055601119995 
//說明:當str_repeat的第二個參數為1時輸出第一個數字,當為8時輸出第二個數字

區別

區別就是str_replace被替換(尋找)的內容是固定的、確定的,當然可以使用變數,但是變數也表示固定的、確定的內容,比如可以完成把所有的\n替換為<br>等場合。

而preg_replace被替換(尋找)的內容是用規則來描述的,比如可以把所有的<和>之間的內容(HTML代碼)替換掉。當然preg_replace也可以用來替換固定內容。

根據以上規則,所有str_replace能做的事情preg_replace都能辦到,但是preg_replace的速度要慢些,使用也要複雜些,所以我們應該儘力使用str_replace。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.