6

I'm using PHP and not really good with regex. I need a preg_replace that can add a space if a letter or number is adjacent.

These are the scenarios:

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

Thanks.

John
  • 1,173
  • 4
  • 13
  • 33

3 Answers3

10

You could use lookarounds to match such positions like so:

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

Depending on how you define "letter" you may want to adjust [a-z].

Lookarounds are required to make it work properly with strings like:

0a1b2c3

Where solutions without would fail.

Qtax
  • 32,254
  • 9
  • 78
  • 117
  • Doesn't work if the number adjacent to the character is negative. – Sayan Bhattacharyya Mar 19 '17 at 14:43
  • @SayanBhattacharyya are there negative street numbers? If you want that feature it's trivial to add the `-` where it's needed. Just replace all the `\d`s with `[-\d]`. – Qtax Mar 19 '17 at 21:56
3

Something like:

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

Should get you far :)

revo
  • 45,845
  • 14
  • 70
  • 113
Evert
  • 83,661
  • 18
  • 106
  • 170
2

Using POSIX classes for portability:

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

gets the the first transition.

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

gets the second.

Graham
  • 1,591
  • 13
  • 22