php - Search a string replace a word with array's value -
the idea search string words , change them else according specific array. let me show mean.
$string = "hello buddy, i'm friend or maybe fellow";
let's friends
swear word. want change word want. made this:
$swears = array( "friend" => "fri**d", "buddy" => "bu**y", "fellow" => "fe**ow" );
i want search string according array's key , replace it's value. did search web replace value in array according array key. after trying came this:
$string = "hello buddy, i'm friend or maybe fellow"; $swears = array( "friend" => "fri**d", "buddy" => "bu**y", "fellow" => "fe**ow" ); $foreach = $string; foreach($swears $bad => $good){ $foreach = str_replace($bad,$good,$foreach); $filtered = $foreach; } echo $filtered;
i know works, there easy way feel complicated whole thing. if i'm good, possible may cause problem, if had large string, or take time process it.
str_replace
might supplied array
of search-words , array
of replacers:
<?php $string = "hello buddy, i'm friend or maybe 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 fri**d or maybe fe**ow
Comments
Post a Comment