Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate an email local-part to '[email protected]'

I use this little function to truncate strings when needed:

function truncate_text($text, $nbrChar = 55, $append='...') {
    if (strlen($text) > $nbrChar) {
        $text = substr($text, 0, $nbrChar);
        $text .= $append;
    } 
    return $text;
}

I would like some help to create a new function to truncate email local-parts similar to what is done in Google Groups.

[email protected]

This would be especially useful for users using Facebook's proxy email.

[email protected]

I guess this new function would use regex to find the @ and then truncate the local-part to a certain number of characters to generate something like

[email protected]

Any suggestions how to tackle this?

Thanks!

like image 759
pepe Avatar asked Oct 29 '11 03:10

pepe


1 Answers

This function will truncate the first part of the email ( if the @ is found ) and other string if @ not found.

function truncate_text($text, $nbrChar = 55, $append='...') {
  if(strpos($text, '@') !== FALSE) {
    $elem = explode('@', $text);
    $elem[0] = substr($elem[0], 0, $nbrChar) . $append;
    return $elem[0] . '@' . $elem[1];
  }
  if (strlen($text) > $nbrChar) {
    $text = substr($text, 0, $nbrChar);
    $text .= $append;
  } 
  return $text;
}

echo truncate_text('[email protected]', 10);
// will output : [email protected]

echo truncate_text('apps+2189712.12457.7b00f3c9e8bfabbeea8f73proxymail.facebook.com', 10);
// will output : apps+21897...
like image 158
Book Of Zeus Avatar answered Nov 07 '22 14:11

Book Of Zeus