簡體   English   中英

從字符串中獲取鍵和值

[英]Getting key and value from string

<?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
)

我在這里做錯了什么?

您可以使用preg_match_all多次應用給定模式來查找字符串中的所有匹配項,並將它們累積到數組中的 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
        )

)

其中索引[0]包含整個正則表達式的所有匹配項,索引[1]包含模式中第一個捕獲組(括號)的匹配項, [2]包含第二個。

然后,您所需要做的就是將[1][2]中的 arrays 合並為一個,因此[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);
}

output 是:

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

請使用 preg_match_all 獲取此類索引,數組中的 0 個索引是匹配項,1 個索引是標簽名稱,2 個索引是標簽值。 1 和 2 索引具有與您需要的鍵值完全相同的 position。

<?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
        )

)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM