PHP正则表达式不起作用

时间:2012-10-31 10:59:46

标签: php regex email

我的一个正则表达式出了问题;如果你可以帮助我:

<?php 
$ptn = "/[\S]*[A-Za-z0-9_-]*.*[A-Za-z0-9_-]+@[A-Za-z0-9_-]*.*[A-Za-z0-9_-]*[\S]*/";
$str = "Contact name: Wahyu van Schneppanginen Email: perm@perotozair.com ";
preg_match($ptn, $str, $matches);
print_r($matches);
?>

结果如何:

   Array
   (
       [0] =>                           Email:                    perm@perotozair.com  
   )

但我想:

   Array
   (
       [0] => perm@perotozair.com  
   )

如果有人能帮助我,我会很高兴

谢谢!

3 个答案:

答案 0 :(得分:1)

这将有效:

<?php 
$ptn = '/[\w\d-]+(?:\.[\w\d-]+)*@[\w\d-]+(?:\.[\w\d-]+)+/';
$str = "Contact name: Wahyu van Schneppanginen Email: perm@perotozair.com bla bla bla xxx@yyy.com";
preg_match_all($ptn, $str, $matches);
print_r($matches);
?>

您的问题是您使用的边界词:[\S]*。您应该使用\b。我还通过对某些部分进行分组,简化并改进了您的正则表达式以匹配电子邮件地址。请注意使用preg_match_all()来匹配字符串中所有出现的电子邮件地址。

<强>输出

Array
(
    [0] => Array
        (
            [0] => perm@perotozair.com
            [1] => xxx@yyy.com
        )

)

答案 1 :(得分:1)

试试这个: -

 <?php 
    $ptn = "/[A-Za-z0-9_-].[A-Za-z0-9_-]+@[A-Za-z0-9_-]*.*[A-Za-z0-9_-]*/";
    $str = "Contact name: Wahyu van Schneppanginen Email: perm@perotozair.com ";
    preg_match($ptn, $str, $matches);
    print_r($matches);
    ?>

答案 2 :(得分:-1)

为什么不使用爆炸?

$str = "Contact name: Wahyu van Schneppanginen Email: perm@perotozair.com ";
$strArr = explode("Email: ",$str);
if(isset($strArr[1]))
    $email = $strArr[1]; //output: perm@perotozair.com
else
    echo "Email not found";
相关问题