关于 PHP 对一篇文章批量替换 不同的值!

WBOY
Libérer: 2016-06-06 20:19:31
original
1476 Les gens l'ont consulté

问下大家 如何 对一篇文章进行对应替换
如 " 我们的祖国是花园,花园的花朵真鲜艳" 替换成 "我们的motherland是花园,花园的flowers真鲜艳" 有一个数组(或者数据库)

<code>祖国=>"motherland" 
花朵=>"flowers" 
</code>
Copier après la connexion
Copier après la connexion

我现在想到的是循环替换 ,有什么其他的更好的方法吗?

回复内容:

问下大家 如何 对一篇文章进行对应替换
如 " 我们的祖国是花园,花园的花朵真鲜艳" 替换成 "我们的motherland是花园,花园的flowers真鲜艳" 有一个数组(或者数据库)

<code>祖国=>"motherland" 
花朵=>"flowers" 
</code>
Copier après la connexion
Copier après la connexion

我现在想到的是循环替换 ,有什么其他的更好的方法吗?

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

都可满足你的需要

二、效率

<code><?php function f1_strtr() {
  for($i=0; $i<1000000; ++$i) {
    $new_string = strtr("aboutdealers.com", array(".com" => ""));
  }
  return $new_string;
}
function f2_str_replace() {
  for($i=0; $i time str_replace => ' . ($time_strtr > $time_str_replace);
?>
--------------------------------------
time strtr       : 3.9719619750977      result :aboutdealers
time str_replace : 2.9930369853973      result :aboutdealers
time strtr > time str_replace => 1

str_replace is faster than strtr</code>
Copier après la connexion

效率上 str_replace > strtr > preg_match

三、str_replace与strtr的一些不同

<code>Be careful when replacing characters (or repeated patterns in the FROM and TO arrays): 

For example: 

<?php $arrFrom = array("1","2","3","B"); 
$arrTo = array("A","B","C","D"); 
$word = "ZBB2"; 
echo str_replace($arrFrom, $arrTo, $word); 
?> 

I would expect as result: "ZDDB" 
However, this return: "ZDDD" 
(Because B = D according to our array) 

To make this work, use "strtr" instead: 

<?php $arr = array("1" => "A","2" => "B","3" => "C","B" => "D"); 
$word = "ZBB2"; 
echo strtr($word,$arr); 
?> 

This returns: "ZDDB"</code>
Copier après la connexion

四、结论

所以一般用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函数传入数组即可

<code>$str = '我们的祖国是花园,花园的花朵真鲜艳';
$result = str_replace(array('祖国','花朵'), array('motherland','flowers'), $str);
echo $result;</code>
Copier après la connexion

PHP自带的字符串替换函数就完全满足你的要求了 建议有需求前去看下官方的手册 很多功能都有函数支持了

Étiquettes associées:
php
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!