preg_replace - don't include string if $4 is blank
Posted
by bradenkeith
on Stack Overflow
See other posts from Stack Overflow
or by bradenkeith
Published on 2010-04-27T15:51:40Z
Indexed on
2010/04/27
15:53 UTC
Read the original article
Hit count: 212
I have this expression:
$regex_phone = '/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})'
.'(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})'
.'[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/';
if(!preg_match($regex_phone, $data['phone'])){
$error[] = "Please enter a valid phone number.";
}else{
$data['phone'] = preg_replace($regex_phone, '($1) $2-$3 ext.$4', $data['phone']);
}
That will take a phone number such as: 803-888-8888 ext 2 as well as 803-888-8888
First number formats as: (803) 888-8888 ext.2 -- the desired effect
Second number formats as: (803) 888-8888 ext. -- blank extension
How can I set it so that if $4 is blank, that ext. won't show?
Thanks so much for any help you can offer. I hope this was clear.
© Stack Overflow or respective owner