Regex: add space if letter is adjacent to number

I use PHP and am not very good at regex. I need a preg_replace that can add a space if a letter or number is next.

These are the scenarios:

mystreet12 -> mystreet 12
mystreet 38B -> mystreet 38 B
mystreet16c -> mystreet 16 c
my street8 -> my street 8

Thank.

+5
source share
3 answers

You can use lookarounds to match these positions:

preg_replace('/(?<=[a-z])(?=\d)|(?<=\d)(?=[a-z])/i', ' ', $str);

Depending on how you define the "letter", you can customize [a-z].

To make it work with strings, for example:

0a1b2c3

Where the solutions are without glitches.

+6
source

Sort of:

preg_replace_all("/([a-z]+)([0-9]+)/i","\\1 \\2", $subject);

It should turn out far :)

+3
source

POSIX :

preg_replace("/([[:alpha:]])([[:digit:]])/", "\\1 \\2", $subject);

.

preg_replace("/([[:digit:]])([[:alpha:]])/", "\\1 \\2", $subject);

.

+2
source

All Articles