Preg split或preg match从具有已知和常量模式的字符串中提取

时间:2015-07-17 04:41:29

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

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

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

1 个答案:

答案 0 :(得分: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