Jump to content

Iterating Characters?


random1

Recommended Posts

Hi,

 

In many ways I'm embarassed that I need to ask this.  :P

 

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

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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.