仅在两个字符串之间移除空白。
I have a string like this: l' opp lop
and I need to remove the white space between l'
and o
, so it has to return l'opp lop
.
我有一个像这样的字符串:l'opp lop我需要删除l'和o之间的空白,所以它必须返回l'opp lop。
But I also need to handle strings with different cases like: L' opp LOP
, L' Opp lop
, l' Opp lop
and return the correct string without the extra space between the those string, so the result has to be: L'opp LOP
, L'Opp lop
, l'Opp lop
.
但我也需要处理不同情况下的字符串,比如L'opp LOP, L'opp LOP, L'opp LOP,返回正确的字符串,而不需要这些字符串之间的额外空间,所以结果必须是:L'opp LOP, L'opp LOP, L'opp LOP。
I have tried $new = str_ireplace( "l' o", "l'o", $string );
but it always returns a string that includes l'o
so if the string is L'Opp lop
the result is always in lower case: l'opp lop
.
我尝试过$new = str_ireplace(“l'o”、“l'o”、$string);但是它总是返回一个包含l'o的字符串,所以如果字符串是l 'Opp lop,结果总是在较低的情况下:l 'Opp lop。
Is it possible to have a solution using regex because I also will need to use it to match l' a
, l' i
, l' u
, l' e
?
使用regex是否可能有一个解决方案,因为我还需要使用它来匹配l' a, l' I, l' u, l' e?
Thanks
谢谢
1 个解决方案
#1
2
You can use
您可以使用
~\b(l)'\s+([a-z])~i
And replace with $1$2
.
和替换为1美元2美元。
See regex demo
查看演示正则表达式
The point is to use capturing groups with the subpatterns that you need to get back after replacement.
重点是使用捕获组和替换后需要返回的子模式。
Regex explanation:
正则表达式的解释:
\b
- starting word boundary- \b -起始字边界
(l)
- match and capture into Group 1 a letterl
orL
(as/i
case insensitive modifier is used)- (l)-将字母l或l匹配并捕获到第1组(使用不区分大小写的修饰符)
'
- a literal apostrophe- ——字面意义上的撇号
\s+
- 1 or more whitespaces (you may use\h+
to limit to horizontal spaces only)- \s+ - 1或更多的白色空间(你可以只使用\h+来限制水平空间)
([a-z])
- match and capture into Group 2 any ASCII letter (lower- and uppercase).- ([a-z]) -匹配并捕获到组2中的任何ASCII字母(小写和大写)。
In the replacement pattern, Group 1 and 2 are backreferences with $1
and $2
respectively.
在替换模式中,第1和第2组分别为$1和$2的反向引用。
更多相关文章
- 在PHP中写入xml时,从字符串中删除&
- 使用PHP捕获正则表达式的字符串的一部分?
- php吧字符串直接转换成数组处理
- 本机PHP函数将授予我直接访问字符串部分而无需创建临时数组的权
- 从JSON字符串/数组中提取第一个图像
- 测试一个字符串是否包含PHP中的单词?
- 几个有用的php字符串过滤,转换函数代码
- PHP - 将字符串转换为键值数组
- PHP空间函数类似于ASP空间()