【问题标题】:Getting key and value from string从字符串中获取键和值
【发布时间】:2020-10-10 05:08:30
【问题描述】:
<?php
// This is my string
$input = "Lorum ipsum [tag=foo]dolor[/tag] sit [tag=bar]amet[/tag] consectetur adipiscing elit.";

// This is my pattern
$pattern = "~\[tag=(.*?)\](.*?)\[/tag\]~s";

// This should output all tags with it's value
$output = preg_split($pattern, $input);
print_r($output);
?>

它输出:

Array ( [0] => Lorum ipsum [1] => sit [2] => consectetur adipiscing elit. )

但我想要:

Array ( 
  [foo] => dolor,
  [bar] => amet
)

我在这里做错了什么?

【问题讨论】:

标签: php arrays preg-split


【解决方案1】:

您可以使用preg_match_all 多次应用给定模式来查找字符串中的所有匹配项,并将它们累积到数组中的输出变量(这是第三个参数)中,如下所示:

Array
(
    [0] => Array
        (
            [0] => [tag=foo]dolor[/tag]
            [1] => [tag=bar]amet[/tag]
        )

    [1] => Array
        (
            [0] => foo
            [1] => bar
        )

    [2] => Array
        (
            [0] => dolor
            [1] => amet
        )

)

其中索引[0] 包含整个正则表达式的所有匹配项,索引[1] 包含模式中第一个捕获组(括号)的匹配项,[2] 包含第二个。

然后您只需将[1][2] 中的数组合并为一个,因此[1] 中的值进入键,[2] 中的值进入新数组的值。这可以使用array_combine

<?php
$input = "Lorum ipsum [tag=foo]dolor[/tag] sit [tag=bar]amet[/tag] consectetur adipiscing elit.";

$pattern = "~\[tag=(.*?)\](.*?)\[/tag\]~s";

// This should output all tags with it's value
if (preg_match_all($pattern, $input, $regexpresult)) {
  $output = array_combine($regexpresult[1], $regexpresult[2]);
  print_r($output);
}

输出是:

Array
(
    [foo] => dolor
    [bar] => amet
)

【讨论】:

    【解决方案2】:

    请使用 preg_match_all 获取此类索引,数组中的 0 索引是匹配项,1 索引是标签名称,2 索引是标签值。 1 和 2 索引与您需要的键值具有相同的确切位置。

    <?php
    // This is my string
    $input = "Lorum ipsum [tag=foo]dolor[/tag] sit [tag=bar]amet[/tag] consectetur adipiscing elit.";
    
    // This is my pattern
    $pattern = "~\[tag=(.*?)\](.*?)\[/tag\]~s";
    
    // This should output all tags with it's value
    preg_match_all($pattern, $input, $output);
    print_r($output);
    
    OUTPUT:
    Array
    (
        [0] => Array
            (
                [0] => [tag=foo]dolor[/tag]
                [1] => [tag=bar]amet[/tag]
            )
    
        [1] => Array
            (
                [0] => foo
                [1] => bar
            )
    
        [2] => Array
            (
                [0] => dolor
                [1] => amet
            )
    
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 2012-08-28
      • 2013-07-02
      • 2018-12-16
      • 2020-07-15
      • 2021-03-13
      • 2019-11-24
      相关资源
      最近更新 更多