Hello Erik,

> Hello everyone,
> I am trying to learn how to use ereg_replace(), but I don't seem to be
> doing it correctly.
> "$phone" is a 10-digit string.
> I want to perform the following:
> $phone = ereg_replace(".{10}", "[part where I am confused]", $phone);
> I would like the output to be
> $phone = "(555) 555-5555";

I would use preg_replace to do this.


$phone = "5555555555";

$phone = preg_replace("/([0-9]{3,3})([0-9]{3,3})([0-9]+)/", "($1) $2-$3",

echo $phone;


The parentheses in the first part of the expression capture what you want.
The stuff between the [and] is a characterclass (in this instance 0 through
The stuff between the curly braces is min,max.

([0-9]{3,3}) Match 0 through 9 a minimum (and max) of three times
([0-9]+) - match at least once.

Hence the number becomes:
($1) $2-$3
($1) = stuff in first parentheses (three digits) - this case, (555)
followed by a space
followed by the next three digits
followed by a dash
followed by whatever's left.
Note that in the second part of the expression, parentheses lose their
"special meaning", and can be used as regular characters (as can the other

You will want to make sure that the numbers when inputted are in the format
you want them when you bring them back out of the file / db whatever -

if (!preg_match("/^[0-9]{10,10}/", $input)) {
// We need 10 numbers!

Hope that helps.


PHP General Mailing List (http://www.php.net/)
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
To contact the list administrators, e-mail: [EMAIL PROTECTED]

Reply via email to