Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带有空格的PHP电子邮件提取器_Php_Regex_Preg Match All - Fatal编程技术网

带有空格的PHP电子邮件提取器

带有空格的PHP电子邮件提取器,php,regex,preg-match-all,Php,Regex,Preg Match All,我有一个从字符串中提取电子邮件的函数 $extractor = function ($str) { $str = str_replace('[at]', '@', $str); $str = str_replace('(dot)', '.', $str); $regexp = '/([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i'; preg_match_all($reg

我有一个从字符串中提取电子邮件的函数

$extractor = function ($str) {
        $str = str_replace('[at]', '@', $str);
        $str = str_replace('(dot)', '.', $str);

        $regexp = '/([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
        preg_match_all($regexp, $str, $m);

        return isset($m[0]) ? $m[0] : [];
    };

    $test_string = 'This is a test string...

        test1@example.org

        Test different formats:
        test2@example.org;
        <a href="test3@example.org">foobar</a>
        <test4@example.org>

        strange formats:
        test5@example.org
        test6[at]example.org
        test7@example.net.org.com
        test8@ example.org
        test9@!foo!.org
        test10.abc [at] hello (dot) com

        foobar
';

    dd($extractor($test_string));

我怎么能忽略正则表达式中的那些空格呢。谢谢。

我建议进一步预处理输入,删除
[at]
(dot)
@
周围的空白,即替换

$str=str_replace(“[at]”、“@”和$str);
$str=str_替换(“(点)”,$str);

$str=preg\u replace('/\s*(?:\[at]|@)\s*/','@',$str);//将[at]或@替换为之前和之后的任意数量的空格@
$str=preg\u replace('/\s*\(点\)\s*/','.',$str);//在使用之前和之后用任意数量的空格替换(点)。
见:

$extractor=函数($str){
$str=preg\u replace('/\s*(?:\[at]\@)\s*/','@',$str);
$str=preg\u replace('/\s*\(点\)\s*/','.',$str);
$regexp='/\b[a-z0-9.-]+@(?[a-z0-9-]+\)+[a-z0-9]{2,4}\b/i';
preg_match_all($regexp,$str,$m);
返回设置($m[0])?$m[0]:[];
};
输出:

Array
(
    [0] => test1@example.org
    [1] => test2@example.org
    [2] => test3@example.org
    [3] => test4@example.org
    [4] => test5@example.org
    [5] => test6@example.org
    [6] => test7@example.net.org.com
    [7] => test8@example.org
    [8] => test10.abc@hello.com
)

你是个天才。谢谢你的帮助:D
Array
(
    [0] => test1@example.org
    [1] => test2@example.org
    [2] => test3@example.org
    [3] => test4@example.org
    [4] => test5@example.org
    [5] => test6@example.org
    [6] => test7@example.net.org.com
    [7] => test8@example.org
    [8] => test10.abc@hello.com
)