3

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?

4 Answers4

7

I don't have 50 rep so I can't comment, but this is just to expand on Moylin's answer:

To make it into 1 query just do as such:

$output_this = preg_replace('/\s+(?=[\.,])/', '', $output_this);

Explanation of the regex:

\s matches a space

+ matches between 1 and infinity times.

(?= ) is a positive lookahead. This means "You have to find this AFTER the main group, but don't include it."

[ ] is a set of characters to match.

\. is an escaped period (Because . matches anything in regex)

and , is a comma!

JDiPierro
  • 802
  • 1
  • 9
  • 28
2

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 ' . '

1
$output_this = preg_replace('/\s+\./', '.', $output_this);
$output_this = preg_replace('/\s+,/', ',', $output_this);

This should be accurate.

Sorry i'm not better to optimize this into a single query for you. edit: removed $ for end of string, not sure you would want it that way.

Moylin
  • 737
  • 1
  • 9
  • 20
0
$content = "This is , some string .";
$content = str_replace( ' .', '.',$content);
$content = str_replace( ' ,', ',',$content);
echo $content;
mdurchholz
  • 523
  • 1
  • 4
  • 16