Kurt Felix
Kurt Felix

Reputation: 33

regex comma before space and number

I am trying to search for every comma before space and a number to remove it.

This is what I have:

Mustardroad, 21, Teststreet 2, Point Place, 5

And this is what I want:

Mustardroad 21, Teststreet 2, Point Place 5            

Upvotes: 0

Views: 96

Answers (3)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89584

Without regex, you can do:

$str = 'Mustardroad, 21, Teststreet 2, Point Place, 5';

$result = array_reduce(explode(', ', $str), function ($c,$i) {
    if (empty($c))
        return $i;
    return is_numeric($i[0]) ? "$c $i" : "$c, $i";
});

With preg_replace: see @Roman or @Toto answers. (eventually with a literal space instead of \s+, if it is what you want)

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

The solution using preg_replace function with specific regex pattern:

$str = 'Mustardroad, 21, Teststreet 2, Point Place, 5';
$str = preg_replace("/,(?=\s+\d)/", "", $str);

print_r($str);

The output:

Mustardroad 21, Teststreet 2, Point Place 5

(?=\s+\d) - lookahead positive assertion, ensures that a comma , is followed by "space and a number"

Upvotes: 2

Toto
Toto

Reputation: 91488

Use this:

$res = preg_replace('/,\s+(?=\d)/', '', $string);

This will remove every comma and following spaces before a digit by nothing.

If you want to keep one space before the digit:

$res = preg_replace('/,\s+(?=\d)/', ' ', $string);

Upvotes: 2

Related Questions