이름과 PHP에서 이메일 주소 또는 사용하여 정규 표현식을 분할하는 방법 :내가 문자열 다음 한
array(
array('name' => 'Test, User', 'email' => '[email protected]'),
array('name' => 'Another, Test', 'email' => '[email protected]'),
...........
)
이름과 PHP에서 이메일 주소 또는 사용하여 정규 표현식을 분할하는 방법 :내가 문자열 다음 한
array(
array('name' => 'Test, User', 'email' => '[email protected]'),
array('name' => 'Another, Test', 'email' => '[email protected]'),
...........
)
preg_match_all()
는 적절한 것 같다
$in = '"Test, User" <[email protected]>, "Another, Test" <[email protected]>, .........';
preg_match_all('!"(.*?)"\s+<\s*(.*?)\s*>!', $in, $matches);
$out = array();
for ($i=0; $i<count($matches[0]); $i++) {
$out[] = array(
'name' => $matches[1][$i],
'email' => $matches[2][$i],
);
}
print_r($out);
출력 :
Array
(
[0] => Array
(
[name] => Test, User
[email] => [email protected]
)
[1] => Array
(
[name] => Another, Test
[email] => [email protected]
)
)
왜 일치하지 않는 당신 preg_split 패턴에 의한 않는 : 나는 결과 다음 원하는
"Test, User" <[email protected]>, "Another, Test" <[email protected]>, .........
:
"Test, User" <test[at]test.com>,
그런 다음 preg_match 이름 및 이메일 구성 요소를 찾으려면 다음을 입력하십시오. 그들을 배열에 넣어 라.
$strs = preg_split($in,'".*" < .* >,');
foreach ($strs as $str){
$in1 = preg_match('/".+"/', $str);
$in2 = preg_match('/< .+ >/', $str);
push($out,array('name'=>$in1,'email'=>$in2);
}
echo $out;
작동하지 않는다. 이름에 쉼표가있다. – cletus
오른쪽 .. 사용할 수 없다. 분할 할 쉼표 ... –
나는 오히려 완벽한 파서 만드는 또 다른 여기에이 답변을 결합 :
function parseEmailListToArray($list) {
$t = str_getcsv($list);
foreach($t as $k => $v) {
if (strpos($v,',') !== false) {
$t[$k] = '"'.str_replace(' <','" <',$v);
}
}
foreach ($t as $addr) {
if (strpos($addr, '<')) {
preg_match('!(.*?)\s?<\s*(.*?)\s*>!', $addr, $matches);
$emails[] = array(
'email' => $matches[2],
'name' => $matches[1]
);
} else {
$emails[] = array(
'email' => $addr,
'name' => ''
);
}
}
return $emails;
}
을 수 ' 아직 코멘트가 없지만 일한다. 이것은 또한 간단한 [email protected]
또는 <[email protected]>
(name
다음 비어)와 일치하고, 따옴표를 둘러싼없이 이름 것
$regex = '/(("([^"]*)"|[^",]*)\\s*<(.*?)>|[^",\\s]+)(?=(,|$))/';
preg_match_all($regex,$in,$matches,PREG_SET_ORDER);
$out = [];
foreach($matches as $match) $out[] = [
'name' => $match[3] ?: trim($match[2]),
'email' => trim($match[4]) ?: $match[1]
];
: 클리 터스에 의해 대답에서 보내고 난에 정규식을 확대했다.
대신에 [^ <>]을 사용하면 더 좋을까요? 이름으로. 그렇다면 점 (.)을 탐욕스럽게 만들 수 있습니까? 두 점 모두에 대해 할 수 있습니다. – Jaskirat
"!" 정규식에서? 그냥 궁금해. – serg
어떤 작품이든 괜찮습니다! 그냥 묻고 ..;) – Jaskirat