Reputation: 570
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.
Upvotes: 0
Views: 4883
Reputation: 89547
the problem is that you choose to put words and replacements as keys and values in one array. A more simple way is to use 2 indexed arrays.
$words = array( 'friend', 'buddy', 'fellow' );
$replacements = array( 'fri**nd', 'bu**dy', 'fe**ow' );
$result = str_replace( $words, $replacements, $yourString );
This way you don't have to create implicitly a new array using array_keys
.
If you absolutely want to store your search/replacements in an associative array, in this case don't use str_replace
and use strtr
:
$swears = array(
"friend" => "fri**d",
"buddy" => "bu**y",
"fellow" => "fe**ow"
);
$filtered = strtr($string, $swears);
Upvotes: 1
Reputation: 12168
str_replace
might be supplied with array
of search-words and array
of replacers:
<?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);
?>
Shows:
hello bu**y, I'm your fri**d or maybe a fe**ow
Upvotes: 9