Php从字符串中的特定标签获取值

时间:2023-02-05 21:26:31

I have a string

我有一个字符串

$string= '<Label>1</Label><Value>1</Value><Label>2</Label><Value>2</Value><Label>3</Label><Value>3</Value><Label>4</Label><Value>4</Value><Label>5</Label><Value>5</Value>';

I need to separate the Label and Value tag values into two separate arrays. I tried to use the following function

我需要将Label和Value标记值分成两个单独的数组。我试着使用以下功能

function getTextBetweenTags($string, $tagname) 
{
    $pattern = "/<$tagname>(.*)<\/$tagname>/";
    preg_match($pattern, $string, $matches, PREG_OFFSET_CAPTURE);
    return $matches;
}

I created another function to make it two separate arrays

我创建了另一个函数来使它成为两个独立的数组

function formatChoices($choices)
{
    $return['label'] = $this->getTextBetweenTags($choices, "Label");
    $return['value'] = $this->getTextBetweenTags($choices, "Value");

    return $return;
}

But it returns the following

但它返回以下内容

Array([label] => Array(
        [0] => 1</Label><Value>1</Value><Label>2</Label><Value>2</Value><Label>3</Label><Value>3</Value><Label>4</Label><Value>4</Value><Label>5
        [1] => 7
    )

[value] => Array
    (
        [0] => 1</Value><Label>2</Label><Value>2</Value><Label>3</Label><Value>3</Value><Label>4</Label><Value>4</Value><Label>5</Label><Value>5
        [1] => 23))

Please help. Thanks

请帮忙。谢谢

3 个解决方案

#1


2  

Try this code.

试试这个代码。

<?php
$string= '<Label>1</Label><Value>1</Value><Label>2</Label><Value>2</Value><Label>3</Label><Value>3</Value><Label>4</Label><Value>4</Value><Label>5</Label><Value>5</Value>';
$array = json_decode(json_encode((array) simplexml_load_string('<data>'.$string.'</data>')),1);
print_r($array);
?>

#2


1  

The inside of tags cannot have '<' and '>' character, so change it this way

标签内部不能包含“<”和“>”字符,因此请按此方式更改

$pattern = "/<$tagname>([^<>]*)<\/$tagname>/";

PS For XML Manipulation it is better to use SimpleXML or DOM or ...

PS对于XML操作,最好使用SimpleXML或DOM或...

#3


0  

The problem is the point it tries to match as match as possible. (The point is greedy.)

问题是它试图匹配尽可能匹配。 (关键是贪心。)

Edit: This should work:

编辑:这应该工作:

$pattern = "/<$tagname>(.*?)<\/$tagname>/";

#1


2  

Try this code.

试试这个代码。

<?php
$string= '<Label>1</Label><Value>1</Value><Label>2</Label><Value>2</Value><Label>3</Label><Value>3</Value><Label>4</Label><Value>4</Value><Label>5</Label><Value>5</Value>';
$array = json_decode(json_encode((array) simplexml_load_string('<data>'.$string.'</data>')),1);
print_r($array);
?>

#2


1  

The inside of tags cannot have '<' and '>' character, so change it this way

标签内部不能包含“<”和“>”字符,因此请按此方式更改

$pattern = "/<$tagname>([^<>]*)<\/$tagname>/";

PS For XML Manipulation it is better to use SimpleXML or DOM or ...

PS对于XML操作,最好使用SimpleXML或DOM或...

#3


0  

The problem is the point it tries to match as match as possible. (The point is greedy.)

问题是它试图匹配尽可能匹配。 (关键是贪心。)

Edit: This should work:

编辑:这应该工作:

$pattern = "/<$tagname>(.*?)<\/$tagname>/";