【问题标题】:Preg split or preg match to extract from string with known and constant patternPreg 拆分或 preg 匹配以从具有已知和恒定模式的字符串中提取
【发布时间】:2015-07-17 04:41:28
【问题描述】:

我有一个充满产品名称的数据库,所有这些都遵循严格且相同的命名模式,例如 European 222/555/111 obtained 我想为表中的每一行运行一个小 php 脚本并提取部分222/555/111 中的 3 个子字符串并将这三个子字符串添加到单独的列中,但我无法进行提取。我应该使用 preg_split 还是 preg_match? 我的字符串都以'European'这个词开头,然后是一个空格,然后我需要用/分隔的三个选项,这些也可能只有2个字符,比如 European 96/43/55c strings strings

应该有 $option1 = 222 $option2 = 555 $option3 = 111

【问题讨论】:

    标签: php preg-match preg-match-all preg-split


    【解决方案1】:

    我会使用preg_match:

    $string = 'European 222/555/111 obtained';
    
    if (preg_match('~European ([^/]+)/([^/]+)/([^/\s]+)~', $string, $matches)) {
        print_r($matches);
    }
    

    输出:

    Array
    (
        [0] => European 222/555/111
        [1] => 222
        [2] => 555
        [3] => 111
    )
    

    说明:

    ~               : regex delimiter
      European\s+   : literally "European" followed by one or more space
      ([^/]+)       : match everything that is not a slash and store in group 1
      /             : a slash
      ([^/]+)       : match everything that is not a slash and store in group 2
      /             : a slash
      ([^/\s]+)     : match everything that is not a slash or a space and store in group 3
    ~               : regex delimiter
    

    【讨论】:

    • 非常感谢,我不能要求更多:)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多