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,243
  • 4
  • 15
  • 34

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
  • 33,241
  • 9
  • 83
  • 121
  • 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
  • 47,783
  • 14
  • 74
  • 117
Evert
  • 93,428
  • 18
  • 118
  • 189
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,631
  • 14
  • 23