dop2144 2015-06-05 20:56
浏览 31
已采纳

PHP从字符串中获取整数[关闭]

I have a massive database storing customers' orders. I have to create a report (monthly and yearly) by total products sales and products brands sales.

The main trouble is that in every order entry, I got a column called items, which stores ordered products info like:

[32] (1 x 22 EUR) prod name wxy
Code:XY
Color:LRC Red Cherry [42] (1 x 33 EUR) prod name fgh
Code:XY
Color:pink [66] (1 x 44 EUR) prod name abc
Code:YU
Color:LPK Pink [60] (6 x 45 EUR) prd name xyz
Code:XY [1965] (1 x 32 EUR) prod name xyz
Code:XY
Color:Yellow [3413] (1 x 74 EUR) product name xyz
Code:XZ [22] (2 x 85 EUR) prod name zzz
Code:XY
Color: Black

The main advantage is that every line is separated by and product ids are in square brackets.

Knowing that I've selected all MySQL entries in a while loop, how could I get all product codes (in this example: 32, 42, 66, ... ) for each order entry (preferabble in an array)?

Rather, how to get only value 32 from this string:

[32] (1 x 22 EUR) prod name wxy
Code:XY
Color:LRC Red Cherry

Note: looking at first 2 lines, there is a <br/> tag between

wxy

and

Code

, but there is always a "before" every [id].

  • 写回答

2条回答 默认 最新

  • doufei1852 2015-06-05 21:03
    关注

    You should restructure your data this is going to be a pain to deal with in the future. You could use a regex with preg_match_all for your current issue.

    <?php
    $string = '[32] (1 x 22 LEI) prod name wxy
    Code:XY
    Color:LRC Red Cherry [42] (1 x 33 LEI) prod name fgh
    Code:XY
    Color:pink [66] (1 x 44 LEI) prod name abc
    Code:YU
    Color:LPK Pink [60] (6 x 45 LEI) prd name xyz
    Code:XY [1965] (1 x 32 LEI) prod name xyz
    Code:XY
    Color:Yellow [3413] (1 x 74 LEI) product name xyz
    Code:XZ [22] (2 x 85 LEI) prod name zzz
    Code:XY
    Color: Black';
    preg_match_all('~\[(\d+)\]~', $string, $ids);
    print_r($ids[1]);
    

    Output:

    Array
    (
        [0] => 32
        [1] => 42
        [2] => 66
        [3] => 60
        [4] => 1965
        [5] => 3413
        [6] => 22
    )
    

    This regex pulls all numbers (\d+) inside []. The tildes are just delimiters saying where the regex starts and ends. The delimiter could be anything but whatever is used will need to be escaped if used in the regex.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP