2011-07-02 162 views
1

我怎样才能从下面的标签值之间的文本:获得两个标签

{desc=1} 
This is a description 
{/desc} 

{desc=1}的数量变化。我也想获得价值。

更新:

也可以在字符串中更desc,例如

{desc=1} 
    This is a description 
{/desc} 
{desc=2} 
    other description 
{/desc} 
... 
+0

您应该使用XML。它会使一切变得更容易。 – esqew

+0

它们可以嵌套吗? – Dogbert

+0

@Dogbert:不,它不能 –

回答

5

这将捕获你想要的一切。

$data = <<<EOT 
{desc=1} 
    This is a description 
{/desc} 
{desc=2} 
    other description 
{/desc} 
EOT; 

preg_match_all('#{desc=(\d+)}(.*?){/desc}#s', $data, $matches); 

var_dump($matches); 

输出:

array(3) { 
    [0]=> 
    array(2) { 
    [0]=> 
    string(44) "{desc=1} 
    This is a description 
{/desc}" 
    [1]=> 
    string(40) "{desc=2} 
    other description 
{/desc}" 
    } 
    [1]=> 
    array(2) { 
    [0]=> 
    string(1) "1" 
    [1]=> 
    string(1) "2" 
    } 
    [2]=> 
    array(2) { 
    [0]=> 
    string(29) " 
    This is a description 
" 
    [1]=> 
    string(25) " 
    other description 
" 
    } 
} 
+0

我只有一个问题,乞讨中的#和最后的#是什么? –

+2

@iUngi,PHP允许你使用几个不同的字符来转义一个正则表达式('/')。我使用它,这样如果我不得不从字面上使用它们,我就不必用'\ /'来转义'/'。 – Dogbert

0

尝试这种

function getInbetweenStrings($start, $end, $str){ 
    $matches = array(); 
    $regex = "/$start([a-zA-Z0-9_]*)$end/"; 
    preg_match_all($regex, $str, $matches); 
    return $matches[1]; 
} 

$str = "{attr1}/{attr2}/{attr3}"; 
$str_arr = getInbetweenStrings('{', '}', $str); 

print_r($str_arr); 
在上面的例子中{和}

是标签,在其间它们的字符串得到萃取。

1

另一个非常简单的方法是我们可以创建一个可以随时调用的简单函数。

<?php 
    // Create the Function to get the string 
    function GetStringBetween ($string, $start, $finish) { 
    $string = " ".$string; 
    $position = strpos($string, $start); 
    if ($position == 0) return ""; 
    $position += strlen($start); 
    $length = strpos($string, $finish, $position) - $position; 
    return substr($string, $position, $length); 
    } 
?> 

,这里是你的问题

$string1=" 
{desc=1} 
This is a description 
{/desc}"; 

$string2=" 
{desc=1} 
This is a description 
{/desc} 
{desc=2} 
    other description 
{/desc}"; 

echo GetStringBetween ($string1, "{desc=1}", "{/desc}"); 
echo GetStringBetween ($string2, "{desc=1}", "{/desc}"); 
echo GetStringBetween ($string2, "{desc=2}", "{/desc}"); 

用法的例子更多细节,请阅读http://codetutorial.com/howto/how-to-get-of-everything-string-between-two-tag-or-two-strings