Avatar of Robert Granlund
Robert Granlund
Flag for United States of America asked on

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?
PHP

Avatar of undefined
Last Comment
Chris Stanyon

8/22/2022 - Mon
Chris Stanyon

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

Norie

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 Hansen

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
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Robert Granlund

ASKER
@chris, do the brackets indicate an array?
ASKER CERTIFIED SOLUTION
Julian Hansen

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Chris Stanyon

Yes - in PHP you can do arrays like so:

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

or

$array = [' ', ':', '"'];