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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.