我想从完整的电子邮件地址获取名称,并尝试了htmlentities和html_entity_decode,但特殊字符<
和>
提供了获取名称的问题。完整的电子邮件地址来自数组(键值)而不是字符串。
Array
(
[ENV_MAIL] => "Project Bribara<project.bribara@gmail.com";
)
// Project email
$environment['ENV_MAIL'] = "Project Bribara<project.bribara@gmail.com";
$projectEmail = $environment['ENV_MAIL'];
echo $projectEmail ;
$projectName = explode("@", htmlentities($adminEmail));
echo html_entity_decode($projectName);
"Project Bribara"
"Project Bribara<project.bribara
如何按预期获得输出?
答案 0 :(得分:2)
你可以这样做。这里我们使用explode()
函数来分割字符串。
$environment['ENV_MAIL'] ="Project Bribara<project.bribara@gmail.com";
echo explode("<",$environment['ENV_MAIL'])[0];
答案 1 :(得分:2)
您可以使用Substr和strpos
Substr将字符串从第一个字符拆分到strpos找到<
的位置。
$str = "Project Bribara<project.bribara@gmail.com";
// Or ^^ is $projectEmail if I understand it correct?
Echo substr($str, 0, strpos($str , "<"));
如果<
导致问题,您可以试试正则表达式吗?
https://regex101.com/r/EfkwLX/1
// Match a-Z and space multiple until non word character
$re = '/([a-zA-Z ]+)\W/';
$str = 'Project Bribara<project.bribara@gmail.com';
preg_match($re, $str, $matches);
Echo $matches[1];
答案 2 :(得分:1)
您应首先使用“&lt; ”将字符串拆分到名称和电子邮件地址。如果您愿意,可以使用“ @ ”拆分。
答案 3 :(得分:-1)
// Project email
$environment['ENV_MAIL'] = "Project Bribara<project.bribara@gmail.com";
$projectEmail = $environment['ENV_MAIL'];
echo $projectEmail;
$projectName = html_entity_decode ($projectEmail);
echo $projectName;
答案 4 :(得分:-1)
您可以通过以下几种方式解决此问题:(Demo Link)
所有其他答案都失败的原因是您错误地表示了输入字符串。您的实际输入字符串包含<
,它是<
的html实体。我的方法将向未来的SO读者阐明这一点,并帮助您为项目选择最佳方法。
$environment['ENV_MAIL']="Project Bribara<project.bribara@gmail.com";
// ^^^^ html entity causing you trouble
$decoded_string=html_entity_decode($environment['ENV_MAIL']); // convert "<" 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('<',$environment['ENV_MAIL']));
输出:
array (
0 => 'Project Bribara',
1 => 'project.bribara@gmail.com',
)
Project Name = Project Bribara
Project Email = project.bribara@gmail.com
array (
0 => 'Project Bribara',
1 => 'project.bribara@gmail.com',
)