Alasdair
Alasdair

Reputation: 14103

PHP preg_replace: remove punctuation from beginning and end of string

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

Upvotes: 7

Views: 5632

Answers (4)

Ry-
Ry-

Reputation: 224857

It depends on what you call punctuation, but:

preg_replace('/^\W*(.+?)\W*$/', '$1', $source);

Upvotes: 4

alex
alex

Reputation: 490153

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

Upvotes: 10

Trott
Trott

Reputation: 70065

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, '?!.');

Upvotes: 8

Gabriel Santos
Gabriel Santos

Reputation: 4974

To keep only alphanumeric chars

preg_replace('/[^a-z0-9]+/i', '', $string);

for ALL ponctuations:

preg_replace('[:punct:]+', '', $string);

Upvotes: 0

Related Questions