[英]Regexp: how to remove everything except another regexp?
i have some regexp (like ^\w+[\w-.] \@\w+((-\w+)|(\w )).[az]{2,3}$, to match correct emails), but i cant figure out how to remove everything that doesn't match the regexp in my string.我有一些正则表达式(如 ^\w+[\w-.] \@\w+((-\w+)|(\w )).[az]{2,3}$, 以匹配正确的电子邮件),但我无法弄清楚如何删除与我的字符串中的正则表达式不匹配的所有内容。
Keeping the email example, i need a way to, given a sting like保留 email 示例,我需要一种方法,例如
$myString = "This is some text, the email is here example@example.com, and other things over here";
i need to return just 'example@example.com', or boolean false, if there is no email in the strings.如果字符串中没有 email,我只需要返回“example@example.com”或 boolean 错误。
Of course, the email is just an example, some others times I'll need to remove everything except integer/floating numbers, etc...当然,email 只是一个例子,有时我需要删除除整数/浮点数等之外的所有内容......
I've googled around so much but didn't find anything.我用谷歌搜索了很多,但没有找到任何东西。
If you surround your regex in parentheses and use preg_match
or preg_match_all
it will only return the part of the string that was matched by the regular expression:如果您将正则表达式括在括号中并使用preg_match
或preg_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);
Note I also took off the beginning and end of string delimeters as in this case they are not needed.请注意,我还取消了字符串分隔符的开头和结尾,因为在这种情况下不需要它们。
Use the preg_match_all
function to match all occurrences.使用preg_match_all
function匹配所有出现。 The preg_match_all
function itself returns the number of matches or false if an error occured. preg_match_all
function 本身返回匹配数,如果发生错误,则返回false 。
So:所以:
$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
}
Your regex needs to have $ and ^ removed in order to work, those symbols cannot be found in the middle of the string.您的正则表达式需要删除 $ 和 ^ 才能工作,在字符串中间找不到这些符号。 If your regex matches it cannot possibly contain anything else but email.如果您的正则表达式匹配,则它不可能包含除 email 之外的任何其他内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.