Regexp:除了另一个正则表达式之外如何删除所有内容?

时间:2009-04-01 20:24:09

标签: php regex

我有一些正则表达式(如^ \ w + [\ w - 。] \ @ \ w +(( - \ w +)|(\ w ))。[az] {2,3} $,以匹配正确的电子邮件),但我无法弄清楚如何删除与我的字符串中的正则表达式不匹配的所有内容。

保持电子邮件示例,我需要一种方法,给出像

这样的刺痛
$myString = "This is some text, the email is here example@example.com, and other things over here";

如果字符串中没有电子邮件,我只需返回'example@example.com'或布尔值为假。

当然,电子邮件只是一个例子,其他一些时候我需要删除除整数/浮点数等之外的所有内容......

我搜索了很多,但没有找到任何东西。

3 个答案:

答案 0 :(得分:4)

如果用括号括起你的正则表达式并使用preg_matchpreg_match_all,它只会返回正则表达式匹配的字符串部分:

$myString = "This is some text, the email is here example@example.com, and other things over here";
preg_match("/(\w+[\w-.]\@\w+((-\w+)|(\w)).[a-z]{2,3})/", $myString, $matches);
print_r($matches);

注意我也取消了字符串分隔符的开头和结尾,因为在这种情况下不需要它们。

答案 1 :(得分:1)

使用preg_match_all function匹配所有匹配项。如果发生错误,preg_match_all函数本身会返回匹配数或 false

所以:

$myString = "This is some text, the email is here example@example.com, and other things over here";
if (($num = preg_match_all('/\w+[\w-.]\@\w+((-\w+)|(\w)).[a-z]{2,3}/', $myString, $matches)) !== false) {
    echo $num.' matches have been found.';
    var_dump($matches);
} else {
    // error
}

答案 2 :(得分:0)

你的正则表达式需要删除$和^才能工作,这些符号在字符串中间找不到。如果您的正则表达式匹配,除了电子邮件之外,它不可能包含任何其他内容。