且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除字符串开头和结尾的特定字符

更新时间:2022-03-19 23:13:43

为什么不直接使用 修剪:

$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 ''