fbpx

Remove Periods, Remove New Lines, Remove Carriage Returns, Remove Tabs, and Remove Spaces from String with PHP

I ran into a problem where I needed to remove periods, new lines, carriage returns, tabs, and spaces from a string with PHP. I tried using preg_replace and was having difficulty getting it to work, so I instead used str_replace using the following function. This worked like a charm. See the code below:

$periods = '.';
$spaces = ' ';
$new_lines = '\n';
$tabs = '\t';
$carriage_returns = '\r';

$find = array($periods, $spaces, $new_lines, $tabs, $carriage_returns);

$replacement = '';

$string = str_replace($find, $replacement, $string);

/*
* In case you don't want to use the find array, you can use the line below
*/
$string = str_replace(array('.', ' ', "\n", "\t", "\r"), $replacement, $string);

Leave a Reply

Your email address will not be published. Required fields are marked *