【问题标题】:How to split this string with preg_match_all in php?如何在 php 中用 preg_match_all 分割这个字符串?
【发布时间】:2019-04-24 18:20:42
【问题描述】:

我需要拆分字符串,例如:

一些描述 art.nr:4457 72 1x ACOUCH 90X200 NICE GREY (3 colli) 1x matras 85x205x12 2x matras 80x190x11 一些规格 14x Premium otherproduct 90x200x23 HR34

我需要的结果是:

  1. 一些描述 art.nr: 4457 72
  2. 1x ACOUCH 90X200 NICE GREY (3 colli)
  3. 1x 矩阵 85x205x12
  4. 2x matras 80x190x11 一些规格
  5. 14x Premium otherproduct 90x200x23 HR34

为了让它更加复杂,第一部分是可选的,但其他部分总是以'1x'左右开头。

我尝试了很多正则表达式,但我无法让它工作。我可以将 preg_split() 与/\s?\d+x\s/ 之类的东西一起使用作为解决方法,但这确实很脏,尽管它分裂得很好。

即使只尝试将第 2 部分拆分到第 5 部分,我也无法正确完成。

我在 php 中用 preg_match_all() 在最简单的字符串上尝试了许多正则表达式模式:

1x ACOUCH 90X200 NICE GREY (3 colli) 1x matras 85x205x12 2x matras 80x190x11 一些规格 14x Premium otherproduct 90x200x23 HR34

以下模式最接近:

  • /(\d+x\s+.+?)(\s+(\d+x\s+.+?(?!\s\d+x\s)))+/i
  • /(\d+x\s+.+)(\s+(\d+x\s+.+))+/i

我认为它应该是这样的:/((\s+)?(\d+x\s+.+(?!\s\d+x\s)))+/i,但它不起作用。

/(\s?\d+x\s+.+)+/i 这样简单的只返回完整的字符串或只返回第一个字符/(\s?\d+x\s+.+?)+/i

我尝试了这些(以及许多其他变体):

我做错了什么?它让我疯狂;这真的不是我的第一个正则表达式!

(以及如何使用可选的第一部分使其适用于完整字符串)

提前致谢!

【问题讨论】:

  • 使用\s+(?=\d+x\s)分割
  • 谢谢!这确实有效!
  • 非常感谢大家的快速和良好的回答。这真的帮助了我! xxx

标签: php regex regex-lookarounds


【解决方案1】:

你为什么不使用这个正则表达式来拆分而不是这么复杂的?

\s+(?=\d+x\s+)

Regex Demo

PHP Code demo

$s = "Some description art.nr: 4457 72 1x ACOUCH 90X200 NICE GRAY (3 colli) 1x matras 85x205x12 2x matras 80x190x11 Some specs 14x Premium otherproduct 90x200x23 HR34";
var_dump(preg_split("/\s+(?=\d+x\s+)/", $s));

打印,

array(5) {
  [0]=>
  string(32) "Some description art.nr: 4457 72"
  [1]=>
  string(36) "1x ACOUCH 90X200 NICE GRAY (3 colli)"
  [2]=>
  string(19) "1x matras 85x205x12"
  [3]=>
  string(30) "2x matras 80x190x11 Some specs"
  [4]=>
  string(39) "14x Premium otherproduct 90x200x23 HR34"
}

【讨论】:

  • 太棒了!!我没有尝试使用前瞻进行拆分:-|这确实很好用!
【解决方案2】:

分手

(?=\b\d+[xX]\b)

a demo on regex101.com

【讨论】:

  • 这确实有效!它忘记使用拆分测试前瞻。谢谢!!
【解决方案3】:

Pushpesh 的正则表达式的冗长方式:

$str = "Some description art.nr: 4457 72 1x ACOUCH 90X200 NICE GRAY (3 colli) 1x matras 85x205x12 2x matras 80x190x11 Some specs 14x Premium otherproduct 90x200x23 HR34";

$words = explode(" ", $str);
$i = 0;
foreach($words as $word){
    if(preg_match("/^\d+x$/", $word)){
        $i++;
    }
    $array[$i][] = $word;
}

foreach($array as $words){
    $split[] = implode(" ", $words);
}

var_dump($split);

输出:

array(5) {
  [0]=>
  string(32) "Some description art.nr: 4457 72"
  [1]=>
  string(36) "1x ACOUCH 90X200 NICE GRAY (3 colli)"
  [2]=>
  string(19) "1x matras 85x205x12"
  [3]=>
  string(30) "2x matras 80x190x11 Some specs"
  [4]=>
  string(39) "14x Premium otherproduct 90x200x23 HR34"
}

【讨论】:

  • 是的,这是老式版本。 ;-) 这总是有效的 ;-) Preg_() 更好。不过还是谢谢!
猜你喜欢
  • 2015-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多