random1 Posted March 1, 2008 Share Posted March 1, 2008 Hi, In many ways I'm embarassed that I need to ask this. I have the following code: function censorWords($search_words, $replacement , $message) { foreach ($search_words as $search_word) { $length = strlen($search_word); $message = eregi_replace("($search_word)", $replacement , $message); } return $message; } How can I get it to replace a word with a number of characters? So it prints out the replacement * times $length. e.g. sentence with a naughty ****, because ***** can be naughty. Link to comment https://forums.phpfreaks.com/topic/93914-iterating-characters/ Share on other sites More sharing options...
QuietWhistler Posted March 1, 2008 Share Posted March 1, 2008 Use the following: $times_star = strlen( $search_word ); for( $i = 0; $i < sizeof( $times_star ); $i++ ) { $replacement .= "*"; } $message = eregi_replace( "($search_word)", $replacement, $message ); Also, a tip: use a check before using a foreach loop, else you'll get an error code which is not very tidy. if( !is_array( $search_words ) ) { return false; } Link to comment https://forums.phpfreaks.com/topic/93914-iterating-characters/#findComment-481209 Share on other sites More sharing options...
random1 Posted March 1, 2008 Author Share Posted March 1, 2008 I ended up with: foreach ($search_words as $search_word) { $length = strlen($search_word); $stringreplacement = ""; for( $i = 0; $i < $length; $i++ ) { $stringreplacement .= $replacement; } $message = eregi_replace("($search_word)", $stringreplacement , $message); } return $message; Seems to work but I'm going to test it more. Link to comment https://forums.phpfreaks.com/topic/93914-iterating-characters/#findComment-481220 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.