多个字符串替换

时间:2011-03-23 05:27:16

标签: php

我需要用它的相关文本替换多个文本

示例:我的字符串类似于:"apple is a great fruit"

现在我需要将"apple"替换为"stackoverflow",将"fruit"替换为"website"

我知道我可以使用str_replace,但还有其他方法吗? str_replace在我的情况下会很慢,因为我需要替换至少5到6个单词

帮助表示赞赏。

3 个答案:

答案 0 :(得分:16)

<?php

$a = array('cheese','milk');
$b = array('old cow','udder');
$str = 'I like cheese and milk';
echo str_replace($a,$b,$str); // echos "I like old cow and udder"

或者,如果您不喜欢这样(担心错过匹配数组值),那么您可以这样做:

$start = $replace = $array();
$str = "I like old cow and udder"

$start[] = 'cheese';
$replace[] = 'old cow';

$start[] = 'milk';
$replace[] = 'udder';
echo str_replace($start,$replace,$str); // echos "I like old cow and udder"

编辑:我看到dnl编辑了这个问题并强调了str_replace太慢的事实。在我对这个问题的解释中,这是因为用户不知道他们会在str_replace中使用数组。

答案 1 :(得分:1)

为了您的目的,str_replace接缝已经是最快的解决方案。

str_replacestrstr

来源:http://www.simplemachines.org/community/index.php?topic=175031.0

答案 2 :(得分:1)

如果您知道所有单词序列并且还替换了单词,则使用以下技术

$trans = array( "apple" => "stackoverflow", "fruit" => "website");
echo strtr("apple is a great fruit", $trans); // stackoverflow is a great website

Reference

相关问题