PHP - Remove all punctuation from the start and end of the string

Viewed 132

I would like to trim all the punctuation and leave only letters or numbers at the beginning and at the end of the string. Any punctuation between letters and numbers should be retained.

This is what I tried from here PHP preg_replace: remove punctuation from beginning and end of string:

$str = '£££2343423 34234238&   ';
    $new = preg_replace('/^\PL+|\PL\z/', '', $str);
    echo $new;

Kindly any recommendations, please?

1 Answers

You can use

$new = preg_replace('/^[^\p{L}0-9]+|[^\p{L}0-9]+\z/u', '', $str);

The regex matches

  • ^[^\p{L}0-9]+ - any one or more chars other than Unicode letters and ASCII digits at the start of string
  • | - or
  • [^\p{L}0-9]+\z - any one or more chars other than Unicode letters and ASCII digits at the end of string.

See the PHP demo online and a regex demo.

Related