PHP preg_replace: remove punctuation from beginning and end of line

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

+6
source share
4 answers

I would not use a regex, maybe something like ...

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

Where the second argument is what you define as punctuation.

Assuming what you really meant is to cut out things that are not letters, numbers, etc., I would go with ...

 $str = preg_replace('/^\PL+|\PL\z/', '', $str); 
+6
source

Perhaps this depends on your definition of punctuation. If it's “nothing but alphanumeric” or something like that, regex can be a way. But if it’s a “period, question mark and exclamation mark” or some other manageable list, it will be easier to understand:

 trim($string, '?!.'); 
+5
source

It depends on what you call punctuation, but:

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

To save only alphanumeric characters

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

for all circuits:

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

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


All Articles