删除字符串开头和结尾的特定字符 [英] Remove specific characters at beginning and end of string
本文介绍了删除字符串开头和结尾的特定字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 PHP,我试图从字符串的末尾和开头删除所有下划线字符.
I am using PHP and I am trying to remove all underscore characters from the end and beginning of a string.
这是字符串:____a_b_c__________
我希望结果是:a_b_c
我已经尝试过这个正则表达式,但它不起作用:
I have tried with this regular expression but it's not working:
preg_replace('/[^a-z]+\Z/i', '', '____a_b_c__________');
推荐答案
为什么不直接使用 修剪:
$string = trim($string, '_');
Regex 用于模式匹配 ___
不是模式,它只是下划线.
Regex is for pattern matching ___
is not a pattern it's just underlines.
但如果我要使用正则表达式,我会这样做:
But if I was gonna use a Regex, I'd do something like this:
$string = preg_replace('/^_+|_+$/', '', $string);
对于正则表达式
^
是一行的开始_
为下划线,+
为一个或多个|
是 OR_
为下划线,+
为一个或多个$
是行尾
^
is the start of a line_
is underline, the+
is one or more|
is OR_
is underline, the+
is one or more$
is the end of line
然后我们只需将其替换为 ''
Then we just replace it with ''
这篇关于删除字符串开头和结尾的特定字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文