Search code examples
phphtml-entitieshtml-encode

Parse name from full email address in PHP


I would like to get name from full email address and tried htmlentities and html_entity_decode but special character < and > gives issue to get the name. As full email address is coming from array (key-value) not as a string.

Array value:

Array
(
   [ENV_MAIL] => "Project Bribara<[email protected]";
)

Tried code:

// Project email
$environment['ENV_MAIL'] = "Project Bribara<[email protected]";
$projectEmail = $environment['ENV_MAIL'];
echo $projectEmail ;
$projectName = explode("@", htmlentities($adminEmail));
echo html_entity_decode($projectName);

Expected:

"Project Bribara"

Actual:

"Project Bribara<project.bribara

How can I get the output as per expected?


Solution

  • There are a few ways that you can tackle this issue: (Demo Link)

    The reason that all of the other answers fail is because you have misrepresented your input string. Your actual input string contains &lt; which is the html entity for <. My methods below will clarify this point to future SO readers and help you to select the best approach for your project.

    $environment['ENV_MAIL']="Project Bribara&lt;[email protected]";
    //                                       ^^^^ html entity causing you trouble
    
    $decoded_string=html_entity_decode($environment['ENV_MAIL']);  // convert "&lt;" to "<"
    var_export(explode('<',$decoded_string));  // generate an array of the two parts for future access
    
    echo "\n\n";
    
    echo "Project Name = ",strstr($decoded_string,'<',true);  // use strstr on < of decoded string with "true" param
    
    echo "\n\n";
    
    echo "Project Email = ",substr($decoded_string,strpos($decoded_string,'<')+1);  // use substr&strpos on <
    
    echo "\n\n";
    
    // or less potentially damaging to your input string...
    var_export(explode('&lt;',$environment['ENV_MAIL']));
    

    Output:

    array (
      0 => 'Project Bribara',
      1 => '[email protected]',
    )
    
    Project Name = Project Bribara
    
    Project Email = [email protected]
    
    array (
      0 => 'Project Bribara',
      1 => '[email protected]',
    )