通过正则表达式按 [char] 拆分,但不按 [char]{2} 拆分
我需要这样做,基本上:
Parameter | Expected Result (array)
a | [a]
a_b | [a, b]
a_b_c | [a, b, c]
a__b | [a_b] <-- note that the double underline be unique
a_b__c | [a, b_c]
我知道如何使用方法 explode
和 str_replace
并使用 foreach
来转换 __
到 _
。基本上是这样的:
<?php
$parameter = 'a_b__c';
$expected = str_replace( '__', "\0", $parameter ); # "a_b\0c"
$expected = explode( '_', $expected ); # ["a", "b\0c"]
foreach ( $expected as &$item )
$item = str_replace( "\0", '_', $item );
# ["a", "b_c"]
?>
但我想使用 preg_*
它可以更快。还是我错了?
好吧,我接受任何更好的建议。 :)
帮助说明:$parameter
将是一个 PHP 标识符(通常是一个类标识符)。
I need do it, basically:
Parameter | Expected Result (array)
a | [a]
a_b | [a, b]
a_b_c | [a, b, c]
a__b | [a_b] <-- note that the double underline be unique
a_b__c | [a, b_c]
I know how I do it with the methods explode
and str_replace
and using a foreach
to converts __
to _
. Basically this:
<?php
$parameter = 'a_b__c';
$expected = str_replace( '__', "\0", $parameter ); # "a_b\0c"
$expected = explode( '_', $expected ); # ["a", "b\0c"]
foreach ( $expected as &$item )
$item = str_replace( "\0", '_', $item );
# ["a", "b_c"]
?>
But I guess that with preg_*
it can be more fast. Or am I wrong?
Well, I accept any better suggestion. :)
Help note: the $parameter
will be ever a PHP identifier (generally a class identifier).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 preg_split 尝试以下方法:
? 和
?!
是零宽度负数 lookaround 断言。You can try the following approach using preg_split:
?<!
and?!
are zero-width negative lookaround assertions.我认为不可能在单个正则表达式操作中进行拆分和替换。
假设您输入了 a_b__c。在第一步中,您可以使用表达式进行拆分(与霍华德给出的相同)
$result = preg_split('/(? 这将为您提供
[a, b__c]
现在,您可以迭代数组中的每个条目并使用
$result = preg_replace('/_(?=_)/', '', $subject); 进行替换这会对你有帮助
将
b__c
替换为b_c
。I do not think it is possible to split and replace in a single regex operation.
Let us say you have input a_b__c. In the first step you can split using the expression (same as what Howard gave)
$result = preg_split('/(?<!_)_(?!_)/', $subject);
which would give you[a, b__c]
Now you can iterate on each of the entry in the array and do the replace using
$result = preg_replace('/_(?=_)/', '', $subject);
which would help youreplace
b__c
withb_c
.