Reputation: 33
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
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
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
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