[英]Remove white space only between 2 strings
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 );
我试过
$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
.但它总是返回一个包含
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
?是否有可能使用正则表达式来解决,因为我还需要使用它来匹配
l' a
、 l' i
、 l' u
、 l' e
?
Thanks谢谢
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 letter l
or L
(as /i
case insensitive modifier is used) (l)
- 将字母l
或L
匹配并捕获到组 1 中(因为使用/i
不区分大小写的修饰符)'
- a literal apostrophe '
- 字面撇号\\s+
- 1 or more whitespaces (you may use \\h+
to limit to horizontal spaces only) \\s+
- 1 个或多个空格(您可以使用\\h+
来限制仅水平空格)([az])
- match and capture into Group 2 any ASCII letter (lower- and uppercase). ([az])
- 匹配并捕获到第 2 组的任何 ASCII 字母(小写和大写)。 In the replacement pattern, Group 1 and 2 are backreferences with $1
and $2
respectively.在替换模式中,组 1 和组 2 分别是
$1
和$2
反向引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.