如何查找字符串并将这些字符串添加到数组中

时间:2014-04-30 07:29:13

标签: php

任何人都请帮帮我..

$description = "This is product description. Quality is good. Title:title Price:1000 Size:XL, Medium, Small  Color:red, green, blue. Any one can buy freely. ";

我想找到"标题:","价格:","尺寸:"和"颜色:"从该字符串,我想在数组中添加这些值。

我想要的输出是:

$new_desc = array(
              'title'=>'title',
              'price'=>1000,
              'size'=>array(
                     [0]=>'XL',
                     [1]=>'Medium',
                     [2]=>'Small',
               ),
              'color'=>array(
                     [0]=>'red',
                     [1]=>'green',
                     [2]=>'blue',
               ),
);

非常感谢!!!

2 个答案:

答案 0 :(得分:0)

使用preg_match_all,您可以find you your identifiers(价格,尺寸......)及其值。然后你必须改变它以适合你的数组形式。

阅读preg_match_all和正则表达式。

<?php

$string = "This is product description. Quality is good. Title:title Price:1000 Size:XL, Medium, Small  Color:red, green, blue. Any one can buy freely. ";
preg_match_all('/([^ ]{1,}):(([0-9a-z]{1,}|([0-9a-z,]{1,})( ))+)/i', $string, $matches);
var_dump($matches);

所以这会给你:

array(6) {
  [0]=>
  array(4) {
    [0]=>
    string(11) "Title:title"
    [1]=>
    string(10) "Price:1000"
    [2]=>
    string(22) "Size:XL, Medium, Small"
    [3]=>
    string(22) "Color:red, green, blue"
  }
  [1]=>
  array(4) {
    [0]=>
    string(5) "Title"
    [1]=>
    string(5) "Price"
    [2]=>
    string(4) "Size"
    [3]=>
    string(5) "Color"
  }
  [2]=>
  array(4) {
    [0]=>
    string(5) "title"
    [1]=>
    string(4) "1000"
    [2]=>
    string(17) "XL, Medium, Small"
    [3]=>
    string(16) "red, green, blue"
  }
  [3]=>
  array(4) {
    [0]=>
    string(5) "title"
    [1]=>
    string(4) "1000"
    [2]=>
    string(5) "Small"
    [3]=>
    string(4) "blue"
  }
  [4]=> [...]
}

如果您遍历此数组中的第一组匹配项,则可以使用stripos轻松创建所需的输出,以查找,explode的出现情况,以便从您的{生成数组{1}}分隔值。

,

可以找到完整的工作DEMO here

答案 1 :(得分:0)

首先使用preg_match_all()提取键值对:

preg_match_all('/[A-Z][a-z]+:[a-z\d, ]+/', $description, $matches);

然后遍历$matches数组并使用explode()创建结果数组:

foreach ($matches[0] as $value) {
    list($key, $qty) = explode(':', $value);

    if (strpos($qty, ',') !== FALSE) {
        $result[strtolower($key)] = array_map('trim', explode(',', $qty));
    } else {
        $result[strtolower($key)] = trim($qty);
    }
}

var_dump($result);

输出:

array(3) {
  ["title"]=>
  string(5) "title"
  ["price"]=>
  string(4) "1000"
  ["color"]=>
  array(3) {
    [0]=>
    string(3) "red"
    [1]=>
    string(5) "green"
    [2]=>
    string(4) "blue"
  }
}

Demo