0

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?

5
  • 2
    So where is $_filename_bad_chars defined. Not in the scope of this function thats for sure Commented Feb 1, 2016 at 23:06
  • Its declared as a public array in the same class :) Commented Feb 1, 2016 at 23:08
  • Well then try $this->_filename_bad_chars and loose the (array) casting unless of course its not an array?? Commented Feb 1, 2016 at 23:08
  • Nothing changed... the function returns the same result. Commented Feb 1, 2016 at 23:10
  • str_replace($bad, '', $fn); returns a string, you are dumping it into the ether, see @Forseti answer Commented Feb 1, 2016 at 23:12

2 Answers 2

4

Seems that:

  1. $_filename_bad_chars should be $this->_filename_bad_chars
  2. str_replace($bad, '', $fn); should be $fn = str_replace($bad, '', $fn);
Sign up to request clarification or add additional context in comments.

2 Comments

Lol, i feel like a total noob right now! Thank you very much guys!
the loop is also surplus, as str_replace accepts arrays
2

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.