PHP 正则表达式用   替换空格如果它跟随单个字母 [英] PHP regex replace white space by   if it is following single letter

查看:83
本文介绍了PHP 正则表达式用   替换空格如果它跟随单个字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有用户定义的字符串(要保存并在网络中使用的 html 格式的字符串),并且需要找到一种方法来用   替换单个字母之后的每个空格.

I have user defined string (html formated string to be saved and used in web) and need to find a way to replace each white space which is right after a single letter by  .

例如 "this is a string" 应该变成 "this is a string",

For example "this is a string" should become "this is a string",

"bla bla bl abla b la blabla" 应该变成 "bla bla b l abla b la blabla" ...等等……

"bla bla b l abla b la blabla" should become "bla bla b l abla b la blabla" ...etc...

推荐答案

preg_replace('/(?<=\b[a-z]) /i', '&nbsp;', $s);

此处的正则表达式执行正向后视确保空格前面是单个字母和单词边界.

The regular expression here performs a positive lookbehind which ensures that the space is preceded by a single letter and a word boundary.

这篇关于PHP 正则表达式用 &amp;nbsp; 替换空格如果它跟随单个字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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