Change a line based on a pattern

I want to change the string in PHP by removing the first and last char, but ONLY if they are equal.

Let me give you a few examples:

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

How should I do it?

Thanks for the help, the regular expression solution works.

+3
source share
1 answer

You can use regex:

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

Regex explanation:

  • ~: delimiters
  • ^: Launch anchor
  • (.): match and remember char (here is its first char)
  • (.*): match something and remember
  • \1: remember the first match
  • $: End anchor
  • $2: remember the second match

Alternatively, you can:

// 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
}   
+6
source

Source: https://habr.com/ru/post/1762285/


All Articles