用于提取具有特定格式的手机号码的正则表达式

RegEx for extracting mobile numbers with a specific format

我有一条来自 mysql 的短信。文本包含 5 种类型的文本。首先是 11 手机号码 ( 01***********) 格式。还有两笔钱,一个交易 ID,包含 10 位大写字母和数字以及一个日期时间。我需要提取每个文本并将其存储在不同的变量中。

示例文本:从 01789788881 成功兑现 Tk 500.00。费用 Tk 0.00。余额 Tk 4,145.08。 TrxID 6E63D2OS4R06/05/2019 20:24.

到目前为止,我试图提取 phone 号码

$sms_text = $result['sms_text'];

preg_match('/\b\d{3}\s*-\s*\d{3}\s*-\s*\d{4}\b/', $sms_text, $sms_from);

echo $sms_from;
echo $cash_in_amount;
echo $fee;
echo $ trx_id;
echo $trx_time;

如何解决这个问题?

您可以使用此正则表达式,并从 group1、group2 和 group3 中提取三个值,当然我可以假设您的 SMS 文本格式相同。

from\s+(\d+).*([a-zA-Z0-9]{10})\s+at\s+(.*)

Regex Demo 1

PHP Code Demo

$sms = 'Cash In Tk 500.00 from 01789788881 successful. Fee Tk 0.00. Balance Tk 4,145.08. TrxID 6E63D2OS4R at 06/05/2019 20:24';
preg_match_all('/from\s+(\d+).*([a-zA-Z0-9]{10})\s+at\s+(.*)/', $sms, $matches);
print('Mobile Number: '.$matches[1][0]."\n");
print('Transaction Id: '.$matches[2][0]."\n");
print('Date Time: '.$matches[3][0]."\n");

输出,

Mobile Number: 01789788881
Transaction Id: 6E63D2OS4R
Date Time: 06/05/2019 20:24

编辑:

要获得 Cash In Tk 500.00 and Fee Tk 0.00,您可以使用以下正则表达式,

(\S+)\s+from\s+(\d+).*Fee\s+Tk\s+(\S+)\..*([a-zA-Z0-9]{10})\s+at\s+(.*)

Regex Demo 2

Updated PHP Demo

$sms = 'Cash In Tk 500.00 from 01789788881 successful. Fee Tk 0.00. Balance Tk 4,145.08. TrxID 6E63D2OS4R at 06/05/2019 20:24';
preg_match_all('/(\S+)\s+from\s+(\d+).*Fee\s+Tk\s+(\S+)\..*([a-zA-Z0-9]{10})\s+at\s+(.*)/', $sms, $matches);
print('Cash In Tk: '.$matches[1][0]."\n");
print('Mobile Number: '.$matches[2][0]."\n");
print('Fee Tk: '.$matches[3][0]."\n");
print('Transaction Id: '.$matches[4][0]."\n");
print('Date Time: '.$matches[5][0]."\n");

打印,

Cash In Tk: 500.00
Mobile Number: 01789788881
Fee Tk: 0.00
Transaction Id: 6E63D2OS4R
Date Time: 06/05/2019 20:24