正则表达式:如果字母与数字相邻,请添加空格 [英] Regex: Add space if letter is adjacent to a number

查看:366
本文介绍了正则表达式:如果字母与数字相邻,请添加空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是PHP,而对正则表达式的使用却不太好.我需要一个preg_replace,如果相邻的字母或数字可以添加一个空格.

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.

这些是方案:

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

谢谢.

推荐答案

您可以使用环视相匹配的位置,例如:

You could use lookarounds to match such positions like so:

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

根据定义字母"的方式,可能需要调整[a-z].

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.

这篇关于正则表达式:如果字母与数字相邻,请添加空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆