Reputation: 1093
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?
Upvotes: 0
Views: 665
Reputation: 492
All 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);
Upvotes: 1
Reputation: 22532
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);
Upvotes: 0
Reputation: 15476
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);
Upvotes: 3
Reputation: 27886
I don't see why you'd need another foreach
for that.
foreach ($swears as $bad_word)
$body = str_ireplace($bad_word, "", $body);
$body = str_replace(":", "-", $body);
But if you did there's nothing stopping you from having another one.
Upvotes: 0
Reputation: 4315
You should just try using http://php.net/manual/en/function.preg-replace.php
Upvotes: 1
Reputation: 4392
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()
.
Upvotes: 3