我有类似下面示例中的文字
$text = "[email protected]:Password
This email is from Gmail
email subscription is valid
[email protected]:password
this email is from yahoo
email subscription is valid ";
我希望能够在没有其余描述的情况下检索文本中的所有电子邮件:密码。我尝试了preg_match但它返回了0个结果并且explode返回所有带有描述的文本。
任何帮助是极大的赞赏
爆炸 Str_Pos 的preg_match
$text = "[email protected]:Password
This email is from Gmail
email subscription is valid
[email protected]:password
this email is from yahoo
email subscription is valid ";
在处理不切实际的输入字符串时很难自信/准确,但这种模式为您提取(不验证)email:password
行。
从行的开头匹配,匹配已知字符,在否定字符类中包括空格字符以防止匹配下一行。如果你愿意,你可以使用\n
而不是\s
。
代码:(Demo)
$text = "[email protected]:Password
This email is from Gmail
email subscription is valid
[email protected]:password
this email is from yahoo
email subscription is valid ";
var_export(preg_match_all('~^[^@\s]+@[^:\s]+:\S+~m', $text, $matches) ? $matches[0]: "none");
输出:
array (
0 => '[email protected]:Password',
1 => '[email protected]:password',
)
...嗯,我想在密码中允许空格是可以的,但如果是这样,那么你就无法从密码右侧修改任何空格。允许空间同时提供分离的捕获组的替代模式可能如下所示:(请参阅带有边缘情况的Demo,其中密码字符需要特定的模式逻辑以防止第一个捕获组中的贪婪匹配。)
var_export(preg_match_all('~([^@\s]+@[^:\s]+):(.*)~', $text, $matches, PREG_SET_ORDER) ? $matches: "none");
我倾向于否定字符类[^...]
而不是.
(任何字符点),因为它允许使用贪婪的量词 - 这提供了模式更高的效率(就步数而言,无论如何)。