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

php中文网
发布: 2016-06-06 20:19:31
原创
1778人浏览过

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

祖国=>"motherland" 
花朵=>"flowers" 
登录后复制

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

回复内容:

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

祖国=>"motherland" 
花朵=>"flowers" 
登录后复制

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

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

立即学习PHP免费学习笔记(深入)”;

都可满足你的需要

二、效率

<?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<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 :aboutdealers
time str_replace : 2.9930369853973      result :aboutdealers
time strtr > time str_replace => 1

str_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: 

<?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"
登录后复制

四、结论

所以一般用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自带的字符串替换函数就完全满足你的要求了 建议有需求前去看下官方的手册 很多功能都有函数支持了

相关标签:
php
PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号