搜索字符串数组值替换一个词 [英] Search a string replace a word with array's value
问题描述
的想法是要搜索的某些单词串,并根据特定的阵列它们变成别的东西。让我告诉你我是什么意思。
The idea is to search a string for certain words and change them into something else according to specific array. Let me show you what I mean.
$string = "hello buddy, I'm your friend or maybe a fellow";
比方说,朋友
是脏话。我想这个词变成我想要的。所以,我提出这样的:
Let's say friends
is a swear word. I want to change this word to what I want. So I made this:
$swears = array(
"friend" => "fri**d",
"buddy" => "bu**y",
"fellow" => "fe**ow"
);
我要根据数组的键搜索的字符串和替换它与它的价值。我没有在网上搜索我得到的是根据数组的键数组中替换值。所以想后,我想出了这一点:
I want to search the string according to the array's key and replace it with it's value. I did search the web all I get is replace a value in the array according to an array key. so after trying I came up with this:
$string = "hello buddy, I'm your friend or maybe a fellow";
$swears = array(
"friend" => "fri**d",
"buddy" => "bu**y",
"fellow" => "fe**ow"
);
$foreach = $string;
foreach($swears as $bad => $good){
$foreach = str_replace($bad,$good,$foreach);
$filtered = $foreach;
}
echo $filtered;
我知道它的工作原理,但有一个简单的方法,我觉得我变得复杂了整个事情。如果我很好,这可能会引起一个问题,如果我有大串,或者需要时间来处理它。
I know it works, but is there an easy way I feel I complicated the whole thing. If I'm good, is it possible it may cause a problem, if I had large string, or take time to process it.
推荐答案
str_replace函数
可能与的搜索词阵列
并提供阵列
替代品的
<?php
$string = "hello buddy, I'm your friend or maybe a fellow";
$swears = array(
"friend" => "fri**d",
"buddy" => "bu**y",
"fellow" => "fe**ow"
);
echo str_replace(array_keys($swears), array_values($swears), $string);
?>
显示:
hello bu**y, I'm your fri**d or maybe a fe**ow
这篇关于搜索字符串数组值替换一个词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!