使用正则表达式将所有进行中的下划线替换为 1 个下划线?
我需要一些帮助,我有一个如下所示的字符串:
$p__________________________________________________________________________________________________________________________________________, &$s___________________________________________________________________________________________________________________________________________, &$k____________________________________________________________________________________________________________________________________________, &$nft_____________________________________________________________________________________________________________________________________________)
并且想知道是否可以使用正则表达式将其变成:
$p_, &$s_, &$k_, &$nft_)
这基本上是删除所有(所以他们没有具体数量,但他们至少 1)进行下划线,并替换它们带有 1 个下划线。
我尝试过以下模式,但没有成功:
preg_replace('#(\$[a-z]{1,3})[_]+#', '$1', $string);
PS:首选 preg_replace (正则表达式)的原因(尽管我知道它并非 100% 总是正确),因为它比使用常规字符串替换函数更精确。
感谢并感谢所有帮助。
I need some help, I have a string which looks like below:
$p__________________________________________________________________________________________________________________________________________, &$s___________________________________________________________________________________________________________________________________________, &$k____________________________________________________________________________________________________________________________________________, &$nft_____________________________________________________________________________________________________________________________________________)
and was wondering if I could use a regex to turn it into:
$p_, &$s_, &$k_, &$nft_)
Which is basically removing all the (so theirs no specific amount but theirs atleast 1) proceeding underscores, and replace them with 1 underscore.
I've tried the following pattern but no luck:
preg_replace('#(\$[a-z]{1,3})[_]+#', '$1', $string);
PS: The reason a preg_replace (regex) is preffered (although I understand its not 100% always correct) because it's more precise then using a regular string replacing function.
Thanks and appreciate all help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
考虑到如此简单的事情,您可以从 str_replace() 获得更好的性能。
thought for something so simple, you'd get better performance from str_replace().
您可以尝试使用“str_replace”将 _ 替换为空格,然后在右侧修剪空格!然后在字符串末尾添加_。我不知道直接的方法抱歉!我认为这比正则表达式更快
you can try replacing _ with space using 'str_replace'and then trim spaces them at right side! and then add a _ at the end of string. I dont know a direct way sorry! imo this is faster than regex
您是在正确的轨道上,只是忘记了变量后面的
_
。如果您需要锚点 -
\$letters 锚点:
#(\$[az]{1,3}_)_+#
和$1
字母锚点:
#([az]_)_+#
与$1
任何锚点:
#((?:^|[^_])_)_+#
与$1
You are on the right track, just forgot a
_
after the variable.If you need an anchor -
\$letters anchor:
#(\$[a-z]{1,3}_)_+#
with$1
Letter anchor:
#([a-z]_)_+#
with$1
Any anchor:
#((?:^|[^_])_)_+#
with$1