Sports Racer
Sports Racer

Reputation: 456

Remove spaces before certain character strings

I can think of "foreach string replace" ways of doing this but feel that a regex replace method would be faster and more elegant, unfortunately regex is not my strongest thing.

I want to take a string like this

23 AB 5400 DE 68 RG

and turn it into

23AB 5400DE 68RG

The number of spaces between the digits and following letters is USUALLY one but could be variable.

I have this example, that is working to find the groups but how do I get rid of the spaces in the replacement?

https://regex101.com/r/ODhpQM/2

This is the code generated by my attempt

$re = '/(\d+ +)(AB|DE|RG|DU)/m';
$str = '23 AB 5400 DE 68 RG
        33 DU 88 DE 8723 AB
        55    RG 76  AB  92 DE';
$subst = '\\1\\2';

$result = preg_replace($re, $subst, $str);

echo "The result of the substitution is ".$result;

Upvotes: 0

Views: 218

Answers (5)

Don't Panic
Don't Panic

Reputation: 41810

Unless I'm missing something, it seems like it would be fine to disregard the digits and just replace any non-digits with spaces before them with the same text without the spaces.

$result = preg_replace('/\s+(\D+)/', '$1', $string);

i.e. match anything like " AB" and replace it with "AB".

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163207

Another option could be:

\b\d+\K\h+(?=(?:AB|DE|RG|DU))\b

That would match between word boundaries \b:

  • \d+ Match 1+ digits
  • \K Forget what was matched
  • (?= Positive lookahead to assert what is on the right
    • (?:AB|DE|RG|DU) Alternation which matches one of the listed values
  • ) close positive lookahead

Regex demo

And replace with an empty string:

$re = '/\b\d+\K\h+(?=(?:AB|DE|RG|DU))\b/';
$str = '23 AB 5400 DE 68 RG';
$result = preg_replace($re, '', $str);
echo $result; // 23AB 5400DE 68RG

Upvotes: 1

suresh bambhaniya
suresh bambhaniya

Reputation: 1687

you can try this

$re = '/(\d+)\s+/';
$str = '23 AB 5400 DE 68 RG 33 DU 88 DE 8723 AB 55    RG 76  AB  92 DE';
$subst = '\\1\\2';

$result = preg_replace($re, $subst, $str);
print_r($result);

Upvotes: 1

anubhava
anubhava

Reputation: 784948

You can use this lookaround regex:

$repl = preg_replace('/(?<=\d)\h+(?=\pL)/', '', $str);

RegEx Demo

Explanation:

  • (?<=\d): Lookbehind to assert we have a digit at previous position
  • \h+: Match 1+ horizontal whitespaces
  • (?=\pL): Lookahead to assert we have a letter ahead of current position

PS: If you want to remove spaces only before some known strings then use this regex:

(?<=\d)\h+(?=(?:AB|DE|RG|DU))

Upvotes: 1

Matt.G
Matt.G

Reputation: 3609

Try Regex: (\d+) +(AB|DE|RG|DU)

Demo

Upvotes: 1

Related Questions