我正在使用PHP来解析电子邮件,并希望获取特定字符串后的数字:例如,我想从此字符串中获取数字033:
Account Number: 033
Account Information: Some text here
Run Code Online (Sandbox Code Playgroud)
总是有一个帐号:这个数字然后换行.我有:
preg_match_all('!\d+!', $str, $matches);
Run Code Online (Sandbox Code Playgroud)
但这只是获得所有数字......
任何帮助都会很棒!谢谢
编辑:
文本是HTML ...可能是问题:
<font face="Arial, Helvetica, sans-serif" color="#000099"><strong><font color="#660000">Account
Number</font></strong><font color="#660000">: 033<br>
<strong>Account Name</strong>: More text here<br>
Run Code Online (Sandbox Code Playgroud)
如果数字始终在Account Number:(包括结尾处的那个空格)之后,那么只需将其添加到正则表达式:
preg_match_all('/Account Number: ([\d]+)/',$str,$matches);
// The parentheses capture the digits and stores them in $matches[1]
Run Code Online (Sandbox Code Playgroud)
结果:
$matches Array:
(
[0] => Array
(
[0] => Account Number: 033
)
[1] => Array
(
[0] => 033
)
)
Run Code Online (Sandbox Code Playgroud)
注意:如果存在HTML,那么它可以包含在正则表达式中,只要您不相信HTML可能会发生变化.否则,我建议使用HTML DOM Parser来获取字符串的纯文本版本并使用正则表达式.
话虽如此,以下是一个包含正则表达式中的HTML并提供与上面相同的输出的示例:
// Notice the delimiter
preg_match_all('@<font face="Arial, Helvetica, sans-serif" color="#000099"><strong><font color="#660000">Account
Number</font></strong><font color="#660000">: ([\d]+)@',$str,$matches);
Run Code Online (Sandbox Code Playgroud)