Remove specific characters at beginning and end of string

亡梦爱人 提交于 2020-01-06 07:14:29

问题


I am using PHP and I am trying to remove all underscore characters from the end and beginning of a string.

Here's the string: ____a_b_c__________
And I want the result to be: a_b_c

I have tried with this regular expression but it's not working:

preg_replace('/[^a-z]+\Z/i', '', '____a_b_c__________');

回答1:


Why not just use trim:

$string = trim($string, '_');

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);

For the regular expression

  • ^ 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 ''



来源:https://stackoverflow.com/questions/49724039/remove-specific-characters-at-beginning-and-end-of-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!