PHP string Replace

PHP $filename = str_replace(' ', '_', $filename);

This will replace the space but I also need to replace a : and ".  I want to replace them with an underscore. (colon and double quote)
Or, is there a way also to escape the Colon also?
LVL 8
rgranlundAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris StanyonWebDevCommented:
You can pass an array into the str_replace() function with all the characters you want to replace:

$filename = str_replace([' ', ':', '"'], '_', $filename);

Open in new window

NorieAnalyst Assistant Commented:
You could try this for replacing the characters.
$search = str_split(" :\"");
$replace ="_";

$filename = str_replace($search, $replace, $filename);

Open in new window


Not sure what you mean about escaping the colon, especially when you are replacing it with an underscore.
Julian HansenCommented:
If you want to santize file names here are some examples

$fname = str_replace(array('\\','/',':','*','?','"','<','>','|'),' ',$filename);

Open in new window

This helper class available here [https://noiselabs.io/2011/04/25/sanitize-filenames-with-php/]
<?php

class Helper
{
    /**
     * Returns a safe filename, for a given platform (OS), by
     * replacing all dangerous characters with an underscore.
     *
     * @param string $dangerousFilename The source filename
     * to be "sanitized"
     * @param string $platform The target OS
     *
     * @return string A safe version of the input
     * filename
     */
    public static function sanitizeFileName($dangerousFilename, $platform = 'Unix')
    {
        if (in_array(strtolower($platform), array('unix', 'linux'))) {
            // our list of "dangerous characters", add/remove
            // characters if necessary
            $dangerousCharacters = array(" ", '"', "'", "&", "/", "\\", "?", "#");
        } else {
            // no OS matched? return the original filename then...
            return $dangerousFilename;
        }

        // every forbidden character is replace by an underscore
        return str_replace($dangerousCharacters, '_', $dangerousFilename);
        }
    }

Open in new window

Usage:
$safeFilename = Helper::sanitizeFileName('#my  unsaf&/file\name?"');

Open in new window


Using regular expressions
// Remove anything which isn't a word, whitespace, number
// or any of the following caracters -_~,;[]().
// If you don't need to handle multi-byte characters
// you can use preg_replace rather than mb_ereg_replace
// Thanks @Łukasz Rysiak!
$file = mb_ereg_replace("([^\w\s\d\-_~,;\[\]\(\).])", '', $file);
// Remove any runs of periods (thanks falstro!)
$file = mb_ereg_replace("([\.]{2,})", '', $file);

Open in new window

Source https://stackoverflow.com/questions/2021624/string-sanitizer-for-filename#answer-2021729
Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

rgranlundAuthor Commented:
@chris, do the brackets indicate an array?
Julian HansenCommented:
From this link http://php.net/manual/en/language.types.array.php
As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].
Which means
$x = ['cow', 'bus driver', 'strawberry'];

Open in new window

Is now the equivalent
$y = array('cow', 'bus driver', 'strawberry')

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Chris StanyonWebDevCommented:
Yes - in PHP you can do arrays like so:

$array = array(' ', ':', '"');

or

$array = [' ', ':', '"'];
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.