Re: preg_replace help [message #173735 is a reply to message #173734] |
Mon, 02 May 2011 12:19 |
Jerry Stuckle
Messages: 2598 Registered: September 2010
Karma:
|
Senior Member |
|
|
On 5/2/2011 7:45 AM, bill wrote:
> unfortunately the documentation, while telling one how to use
> preg_replace, does not tell how to write a regular expression.
>
> In this case google is not my friend as the tutorial I read suggested
> (as _I_ read it):
>
> $contact = preg_replace("[0-9\-]*","",$contact);
>
> when I want to return a string that contains only numbers or the hyphen
> (a telephone number in the US).
>
> preg_replace does not like the * which the tutorial says means "do it
> over and over"
>
> and $contact = preg_replace("[0-9\-]","",$contact);
> doesn not modify the string at all.
>
> a bit of help (or a lot of help) would be appreciated (no, I have not
> been in school for quite some time, Jerry)
>
> bill
You're close, Bill, but you have a couple of problems.
First of all, the PHP preg_xxx() functions require a separator character
around the search string. Stupid, I know, but then there are a lot of
stupid things in PHP.
To get rid of your error, you need something like:
$contact = preg_replace("/[0-9\-]*/","",$contact);
However, this will replace all digits and hyphens with a null string -
just the opposite of what I think you need to do. So you need to negate
the character class, i.e.
$contact = preg_replace("/[^0-9\-]*/","",$contact);
Should get you what you want.
However, if you're trying to "clean up" user input, I recommend you not
do this. Rather, check to see if there are any invalid characters in
the input, and if so, return an error message to the user. Nothing is
quite so annoying as accidentally hitting "y" instead of "6" and not
noticing it when you type it in - and having the "y" just dropped from
the number, leaving an invalid phone number.
And BTW - I don't know why you would think I would take this as a
homework problem.
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex(at)attglobal(dot)net
==================
|
|
|