Andrei Vlad
Andrei Vlad

Reputation: 315

PHP - If a word contains a certain string replace it

I have an array with bad strings that i want to replace in certain words, currently i wrote this code to manage this but its not working as it should:

public function _clean_filename($fn)
{
    if($fn === '')
        return;

    foreach((array)$_filename_bad_chars as $bad)
    {
        if(strpos($fn, $bad))
        {
            str_replace($bad, '', $fn);
        }
    }
    return $fn;
}

Simptom: When i input a word with bad strings in it the function returns nothing.

How should i rewrite this code to make it functional?

Upvotes: 0

Views: 184

Answers (2)

Steve
Steve

Reputation: 20459

you can simplify the whole method:

public function _clean_filename($fn)
{        
    return str_replace($this->_file_bad_chars, '', $fn);
}

str_replace accepts arrays for all parameters, and given an empty string for subject will return an empty string

also, your use of a leading underscore for a public method is odd!

Upvotes: 2

Forseti
Forseti

Reputation: 2945

Seems that:

  1. $_filename_bad_chars should be $this->_filename_bad_chars
  2. str_replace($bad, '', $fn); should be $fn = str_replace($bad, '', $fn);

Upvotes: 4

Related Questions