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.
\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.
You can match a space character with just the space character; [^ ] matches anything but a space character.
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."
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.
Something like:
preg_replace("/([a-z]+)([0-9]+)/i","\\1 \\2", $subject);
Should get you far :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With