简体   繁体   中英

Change a string based on a pattern

I want to change a string in PHP by deleting the first and the last char but ONLY IF they are equal.

Let me give some examples:

' abc ' should become 'abc'
'abc a' should become 'bc '
' abc a' should not change

How do I do it?

Thanks for the help, the regex based solution works.

You can use the regex:

$str = preg_replace('~^(.)(.*)\1$~','$2',$str);

Regex explanation:

  • ~ : Delimiters
  • ^ : Start anchor
  • (.) : match and remember a char ( here its the first char)
  • (.*) : match anything and remember
  • \\1 : recall the first match
  • $ : End anchor
  • $2 : recall the 2nd match

Alternatively you can do:

// if string has >1 char and 1st and last char as same.
if(strlen($str) > 1 && $str[0] == $str[strlen($str)-1]) {
  $str = substr($str,1,strlen($str)-2); // extract the substring
}   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM