Here is my current code:
foreach ($swears as $bad_word)
$body = str_ireplace($bad_word, "", $body);
It's filtering bad words, but I'd like to also filter a ":" to a "-" in the body. How can I have multiple foreach statements in my script?
Use curly brackets?
foreach( $swears as $bad_word )
{
$body = str_ireplace($bad_word, "", $body);
$body = str_ireplace(":", "-", $body);
}
or arrays in str_ireplace:
foreach( $swears as $bad_word )
$body = str_ireplace(array(":", $bad_word), array("-", ""), $body);
: replace? It will do something the first time, and then make no further modifications. It's best to put that outside the loop. Or even better, don't use a loop: $body = str_ireplace($swears, '', $body); $body = str_replace(':', '-', $body);Put them right after each other?
Eg:
foreach($swears as $bad_word)
$body = str_ireplace($bad_word, '', $body);
$replace_chars = array(
':' => '-',
'?' => '!');
foreach($replace_chars as $char => $rep)
$body = str_replace($char, $rep, $body);
If you only have one additional character you want to replace, just use str_replace() again, by itself, outside of the foreach(), instead of using the $replace_chars array and the second foreach().
preg_replace is considerably more complicated that having two foreach statementsAll the responses are terrible. You don't need a foreach loop. Here's how it should be done:
$filter = array(
':' => '-',
'badword' => '',
'anotherbad' => ''
);
$body = str_ireplace(array_keys($filter), $filter, $body);
$body = str_ireplace(array(':','badword','anotherbad'),array('-'), $body);? Or do you just want to settle down a little?You can use arrays in stri_replace
$body = str_ireplace($bad_words, '', $body);
$body = str_replace(':', '-', $body);
Another way to do it with a single replace, which works well if you have more filter arrays (you could use array_merge to add more replacements)
$filters = $bad_words;
$replacements = array_fill(0, count($bad_words), '');
$filters[] = ':';
$replacements[] = '-';
$body = str_ireplace($filters, $replacements, $body);
'' string will suffice...
strtr($body, $swears)(documentation: php.net/manual/en/function.strtr.php) for bad word replacement too. (Requires some alteration to the $swears array:$swear => $replacement)