Gasim
Gasim

Reputation: 7961

format text using a string

I am want to format a text from using a string as the formatter. Something like this:

echo formatText('5555555555','(ddd) ddd-dddd');

which will give me result

(555) 555-5555

How can I achieve that?

Thanks, Gasim

Upvotes: 0

Views: 65

Answers (2)

Ruben Serrate
Ruben Serrate

Reputation: 2783

Have a look at sprintf I think it's what you're looking for

echo sprintf("(%d) %d-%d",$prefix, $first-part, $second-part);

or

printf("(%d) %d-%d",$prefix, $first-part, $second-part);

Upvotes: 1

Jon
Jon

Reputation: 437336

One way would be to use preg_replace to match valid input and format it as desired:

echo preg_replace('/^(\d{3})(\d{3})(\d{4})$/', '($1) $2-$3', '5556667777');

Upvotes: 1

Related Questions