Adrian33
Adrian33

Reputation: 291

Removing all non-alphanumeric characters at end of string

How does one remove all non-alphanumeric characters at the end of a string. Eg:

Quick @# brown fox -  
Quick @# brown fox##  
Quick @# brown fox  
Quick @# brown fox @$#  

all become

Quick @# brown fox

Seeking to possibly use preg_replace because ereg_replace is deprecated.

It could also be tweaked to allow specific non-alphanumeric characters at end of string, eg quotes, exclamation marks, question marks

Upvotes: 0

Views: 3137

Answers (2)

James Kyburz
James Kyburz

Reputation: 14453

$rep = preg_replace('/\W+$/', '', $str);

Upvotes: 1

Poelinca Dorin
Poelinca Dorin

Reputation: 9703

$str = 'Quick @# brown fox @$#';
$rep = preg_replace('/[^a-z0-9]+\Z/i', '', $str);
var_dump($rep);

Upvotes: 6

Related Questions