Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP preg_replace: remove punctuation from beginning and end of string

Tags:

regex

php

What regular expression can I use in PHP to remove all punctuation from the beginning and end of a string?

like image 655
Alasdair Avatar asked Nov 27 '11 03:11

Alasdair


2 Answers

I wouldn't use a regex, probably something like...

$str = trim($str, '"\'');

Where the second argument is what you define as punctuation.

Assuming what you really meant was to strip out stuff which isn't letters, digits, etc, I'd go with...

$str = preg_replace('/^\PL+|\PL\z/', '', $str);
like image 68
alex Avatar answered Oct 21 '22 04:10

alex


Might depend on your definition of punctuation. If it's "anything but alphanumerics" or something like that, then a regular expression may be the way to go. But if it's "period, question mark, and exclamation point" or some other manageable list, this will be easier to understand:

trim($string, '?!.');
like image 39
Trott Avatar answered Oct 21 '22 03:10

Trott