简体   繁体   English

如何使用 php 或 sql 对已存储在 sql 列中的字符串句子中的数字求和

[英]How do I sum numbers inside a string sentence already stored in sql column using php or sql

MEL1INFA73 Confirmed. Ksh29.00 sent to Safaricom Offers  for account Tunukiwa on 21/5/18 at 3:29 AM New M-PESA balance is Ksh5.50. Transaction cost, Ksh0.00.

An example of the string sentence is as above and the layout in sql table is as below:字符串语句的例子如上,sql表中的布局如下:

在此处输入图片说明

You can use preg_match_all (regex) and array_sum.您可以使用 preg_match_all (regex) 和 array_sum。

The regex captures all digits with leading ksh and optional space.正则表达式捕获所有带有前导 ksh 和可选空格的数字。

Array_sum sums the digits captured in the regex, since preg_match returns a multidimensional array with 0 being the full match and 1 being the capture. Array_sum 对正则表达式中捕获的数字求和,因为 preg_match 返回一个多维数组,其中 0 是完全匹配,1 是捕获。

$str ='MEL1INFA73 Confirmed. Ksh29.00 sent to Safaricom Offers  for account Tunukiwa on 21/5/18 at 3:29 AM New M-PESA balance is Ksh5.50. Transaction cost, Ksh0.00.';

preg_match_all("/ksh\s*(\d+\.\d+)/i", $str, $matches);
echo array_sum($matches[1]); //34.5

https://3v4l.org/A2oNM https://3v4l.org/A2oNM

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM