Jump to content

[SOLVED] preg_replace/ pulling mysql data for zip code and e-mail


BandonRandon

Recommended Posts

Hello,

 

I have searched for forum for an answer and looked at countless websites. However, Regex is just something i don't understand. I view myself as more of a designer than a programmer my friends say i should just stick to design but that's another story.

 

Here's what I'm trying to do, I'm storing my zip code, and phone number into the database as strings of numbers with no formating then trying to use preg_replace to put them into a format that looks nice on the page. Everything is working but i'm sure on a few things. How to make the zip code only have a dash if there is more than 5 digits and how to make the e-mail in the format name[at]domain[dot]com.

 

here is the code:

function MakeHyperlink($text) {
$text = preg_replace("/((http(s?):\/\/)|(www\.))([\S\.]+)\b/i","<a href=\"http$3://$4$5\" target=\"_blank\">$2$4$5</a>", $text); // url replace
$text = preg_replace("/([\w\.]+)(@)([\S\.]+)\b/i","<a href=\"mailto:$1[at]$3\">$1[at]$3</a>",$text); //e-mail replace
$text = preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $text); //phone number replace
$text = preg_replace("/([0-9]{5})([0-9]{4})?/", "$1-$2", $text); //zip code replace
return nl2br($text);}

 

Thanks,

Brandon

 

<?php
$text = '123456789, 12345, [email protected]';
$text = preg_replace("/([\w\.]+)(@)(([^\s\.]+)(\.)([^\s]*))/i","<a href=\"mailto:$1[at]$3\">$1[at]$4[dot]$6</a>",$text); //e-mail replace
$text = preg_replace("/([0-9]{5})([0-9]{4})/", "$1-$2", $text); //zip code replace
echo $text;
?>

Some additions:

 

  • Added shorthands
  • There's no need to escape . inside of a character class
  • Added a possessive to prevent backtracking before @
  • Changed enclosing quotes to avoid unnecessary escapes
  • Removed unnecessary parentheses

 

<pre>
<?php
$text = '123456789, 12345, [email protected]';
$text = preg_replace(
'/([^@\s]++)@([^\s.]+)\.(\S+)/i',
'<a href="mailto:$1[at]$2[dot]$3">$1[at]$2[dot]$3</a>',
$text
);
$text = preg_replace(
'/(\d{5})(\d{4})/',
'$1-$2',
$text
);
echo $text;
?>
</pre>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.