获取字符串后的数字php正则表达式
我正在使用PHP解析电子邮件并希望获得特定字符串后的数字: 例如,我想从此字符串获取数字033:获取字符串后的数字php正则表达式
Account Number: 033
Account Information: Some text here
总是有单词帐号:然后是数字,然后是换行符。我有:
preg_match_all('!\d+!', $str, $matches);
但是,这只是让所有的数字...
任何帮助将是巨大的! 感谢
编辑:
的文字是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>
如果Account Number:
后数量始终(包括在最后那个空间),那么就添加到您的正则表达式:
preg_match_all('/Account Number: ([\d]+)/',$str,$matches);
// The parentheses capture the digits and stores them in $matches[1]
结果:
$matches Array:
(
[0] => Array
(
[0] => Account Number: 033
)
[1] => Array
(
[0] => 033
)
)
注:如果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);
这是返回一个空阵列...可能是这是来自电子邮件?我也使用quoted_printable_decode():$ fullBody = imap_fetchbody($ mbox,$ email_number,1.0); \t \t \t $ str = quoted_printable_decode($ fullBody); – Bill 2013-03-23 00:21:24
这可能是因为文字中的隐藏字符。复制并粘贴您的文本,并且它可以在www.myregextester.com上使用。 – Josh 2013-03-23 00:27:09
嗯...所以我需要将HTML转换为纯文本也许.... – Bill 2013-03-23 00:27:42
$str = 'Account Number: 033
Account Information: Some text here';
preg_match('/Account Number:\s*(\d+)/', $str, $matches);
echo $matches[1]; // 033
你并不需要使用preg_match_all()
你也没有把你的比赛放在括号内,作为反向引用。
以该HTML为基础:
$str = '<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>';
preg_match_all('!Account Number:\s+(\d+)!ims', strip_tags($str), $matches);
var_dump($matches);
,我们得到:
array(2) {
[0]=>
array(1) {
[0]=>
string(19) "Account Number: 033"
}
[1]=>
array(1) {
[0]=>
string(3) "033"
}
}
+1我忘了'strip_tags'。如果这有效,那么这应该是答案。 – Josh 2013-03-23 00:48:49
有不仅仅是这在较大的字符串更多的数字(我只是拿了一块),所以我不仅会想要“帐号”后面的数字,而不是其他数字 – Bill 2013-03-23 00:13:17
它们可能不一定是 – Bill 2013-03-23 00:14:47
这个HTML是畸形的顺便说一句。 – 2013-08-22 10:44:10