Search code examples
phpstr-replace

Remove spaces before periods ? str_replace


I'm trying to remove all spaces before period and commas from a text before i echo it.

The text could look like this , and have spaces all over . Bla bla bla...

Here is my code, although it successfully removes any ( ) and replaces it with "nothing":

$strip_metar = array('( )' => '', ' . ' => '. ', ' , ' => ', ');
$output_this = $text->print_pretty();
$output_this = str_replace(array_keys($strip_metar),
                           array_values($strip_metar),
                           $output_this);

Any ideas?


Solution

  • To remove all spaces before period. and comma, you can pass arrays to the str_replace function:

    $output_this = str_replace(array(' .',' ,'),array('.',','),$string);

    In the example you have provided, you will not strip spaces before a period, if the period is not followed by a space ' . '