Re: String formatting using preg_replace

From: Date: Tue, 13 May 2003 14:49:56 +0000
Subject: Re: String formatting using preg_replace
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-147442@lists.php.net to get a copy of this message
> Greetings learned PHP(eople), Howdy... > Objective : Strip out all occurrences of the following from a string : > /?<>,.;':"`!@#$%^&*()1234567890-+=\| > ....and replace them with nothing > > Code : > $compname = 'Joe`s Garage Inc.'; > $trim1 = trim($compname); > $cust_dir = preg_replace("/`1234567890 /","",$trim1); The first parameter to preg_replace is a pattern that you want replaced. You're telling preg_replace to look for that exact pattern of numbers to replace, instead of any single number. Since it doesn't find that pattern anywhere, nothing is replaced and you end up with the original string. What you want to tell preg_replace is to look for any of these characters and replace it with an empty string. You'd accomplish that by using: $cust_dir = preg_replace("/['0123456789]/",'',$trim1); Notice the [ and ] characters. You'll match any of those characters now and replace them. For example, if you had a pattern such as "/a[0-9]a/", then that'll match the letter 'a' followed by single number zero through nine, followed by another letter 'a'. So "a1a" and "a9a" would be matched, but "a99a" would not because you're looking for a single number. Hope that helps. > Am I right in assuming that str_replace can only replace one character, > i.e. you can`t specify many things to replace You can if you use arrays. Pretty sure there are examples in the manual. ---John Holmes...

« previous php.general (#147442) next »