關於 PHP 對一篇文章批量替換 不同的值!

來源:互聯網
上載者:User
問下大家 如何 對一篇文章進行對應替換
如 " 我們的祖國是花園,花園的花朵真鮮豔" 替換成 "我們的motherland是花園,花園的flowers真鮮豔" 有一個數組(或者資料庫)

祖國=>"motherland" 花朵=>"flowers" 

我現在想到的是迴圈替換 ,有什麼其他的更好的方法嗎?

回複內容:

問下大家 如何 對一篇文章進行對應替換
如 " 我們的祖國是花園,花園的花朵真鮮豔" 替換成 "我們的motherland是花園,花園的flowers真鮮豔" 有一個數組(或者資料庫)

祖國=>"motherland" 花朵=>"flowers" 

我現在想到的是迴圈替換 ,有什麼其他的更好的方法嗎?

一、在PHP中替換有三種方式
1、strstr
2、str_replace
3、preg_match

都可滿足你的需要

二、效率

 ""));  }  return $new_string;}function f2_str_replace() {  for($i=0; $i<1000000; ++$i) {    $new_string = str_replace( ".com", "", "aboutdealers.com");  }  return $new_string;}$start = microtime(true);$strtr = f1_strtr();$stop = microtime(true);$time_strtr = $stop - $start;$start = microtime(true);$str_replace = f2_str_replace();$stop = microtime(true);$time_str_replace = $stop - $start;echo 'time strtr       : ' . $time_strtr       . "\tresult :" . $strtr       . "\n";echo 'time str_replace : ' . $time_str_replace . "\tresult :" . $str_replace . "\n";echo 'time strtr > time str_replace => ' . ($time_strtr > $time_str_replace);?>--------------------------------------time strtr       : 3.9719619750977      result :aboutdealerstime str_replace : 2.9930369853973      result :aboutdealerstime strtr > time str_replace => 1str_replace is faster than strtr

效率上 str_replace > strtr > preg_match

三、str_replace與strtr的一些不同

Be careful when replacing characters (or repeated patterns in the FROM and TO arrays): For example:  I would expect as result: "ZDDB" However, this return: "ZDDD" (Because B = D according to our array) To make this work, use "strtr" instead:  "A","2" => "B","3" => "C","B" => "D"); $word = "ZBB2"; echo strtr($word,$arr); ?> This returns: "ZDDB"

四、結論

所以一般用str_replace , 需要正匹配的時候用preg_match

http://php.net/manual/en/function.str-replace.php
http://php.net/manual/zh/function.strtr.php

http://www.w3school.com.cn/php/func_string_str_replace.asp

用str_replace函數傳入數組即可

$str = '我們的祖國是花園,花園的花朵真鮮豔';$result = str_replace(array('祖國','花朵'), array('motherland','flowers'), $str);echo $result;

PHP內建的字串替換函數就完全滿足你的要求了 建議有需求前去看下官方的手冊 很多功能都有函數支援了

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.