简体   繁体   中英

preg_replace help: phone number

I need a little help here. This code correctly displays every format I enter--except when it's xxx.xxx.xxxx

It keeps the periods in! How do I filter out periods too?

preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "$1-$2-$3", $phone_enter)

You need to update the query so it will allow a . (dot), i added the \\.? which means, a dot may appear zero or one time.

preg_replace("/([0-9]{3})\.?([0-9]{3})\.?([0-9]{4})/", "$1-$2-$3", $phone_enter)

I would do this:

preg_replace('/(\d{3})([.-])?(\d{3})\2(\d{4})/', '$1-$3-$4', $phone_number);

\\d is shorthand for [0-9] . The use of the backreference means you can enter "123.456.7890" or "123.456.7890" but not "123.4567890" or "123.456-7890".

Also bear in mind that other countries have different phone number formats, if that's relevant to what you're doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM