Home > Backend Development > PHP Tutorial > 字符串替换,怎么能做到双向替换

字符串替换,怎么能做到双向替换

WBOY
Release: 2016-06-13 13:27:18
Original
1022 people have browsed it

字符串替换,如何能做到双向替换?
最近要做一个同义词替换的功能,因为是同义词,所以最好是能双向替换,比如“拜会”和“拜见”,在字符串中出现任何一个都要能替换成另一个。

通常用str_replace只能单向替换,不能实现双向替换。

尝试了一下把同义词做成数组再用str_replace替换,结果却不正确。

$find = array("拜会","拜见");
$replace = array("拜见","拜会");
$arr = array("拜会和拜见");
str_replace($find,$replace,$arr);

结果是:拜会和拜会。

问题是怎么样才能使最后的替换结果是“拜见和拜会”?


------解决方案--------------------
改动一下

PHP code

$find = array("拜会","拜见");
$replace = array("拜见","拜会");
$str = "拜会和拜见";
echo    strtr($str, array_combine($find, $replace)); <div class="clear">
                 
              
              
        
            </div>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template