Jump to content

finding an email in a text


AviNahum

Recommended Posts

hey,

im trying to recognize an email address in a text paragraph, for example:

 

1111111 <br/> [email protected] <br/> 22222

 

and replace it to:

 

1111111 <br/> <a href="mailto:[email protected]">[email protected]</a> <br/> 22222

 

it's my first time dealing with regex and so far i reached this:

 

$text = "1111111 <br/> [email protected] <br/> 22222";
$post_eregi = '/(.)([^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4})(.)/';

echo preg_replace($post_eregi, "<a href='mailto:$2'>$2</a>", $text);

 

unfortunately it doesnt work :(

 

but if i remove the breakline  tag before the email address it's works grate! any suggestions or ideas what wrong?

 

thanks in advance!

Link to comment
https://forums.phpfreaks.com/topic/257092-finding-an-email-in-a-text/
Share on other sites

hello, you can use something like this:

 

$pattern = "~\b([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4})\b~";
$str = "1111111 <br/> [email protected] <br/> 22222";
$replacement = '<a href="mailto:$1">$1</a>';
echo preg_replace($pattern, $replacement,$str);

 

results:

 

1111111 <br/> <a href='mailto:[email protected]'>[email protected]</a> <br/> 22222

 

append an i modifier to the end of the pattern to make it case insensitive, I was hoping you would take some initiative and see that.

 

$pattern = "~\b([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4})\b~i";
$str = "1111111 <br/> [email protected] <br/> 22222";
$replacement = '<a href="mailto:$1">$1</a>';
echo preg_replace($pattern, $replacement,$str);

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.