Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: Add space if letter is adjacent to a number

Tags:

regex

php

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.

like image 477
John Avatar asked Jun 13 '12 22:06

John


People also ask

How do you add a space in regex?

\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.

How do I match a character except space in regex?

You can match a space character with just the space character; [^ ] matches anything but a space character.

How do you escape a space in regex?

The backslash in a regular expression precedes a literal character. You also escape certain letters that represent common character classes, such as \w for a word character or \s for a space. The following example matches word characters (alphanumeric and underscores) and spaces. "there, Alice?, asked Jerry."


2 Answers

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.

like image 159
Qtax Avatar answered Sep 17 '22 23:09

Qtax


Something like:

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

Should get you far :)

like image 44
Evert Avatar answered Sep 19 '22 23:09

Evert