获取两个标签之间的文本

时间:2011-07-02 19:16:59

标签: php preg-match

如何从以下标记中获取值:

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

{desc=1}中的数字正在发生变化。我也希望得到这个价值。

更新:

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

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

3 个答案:

答案 0 :(得分: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
"
  }
}

答案 1 :(得分: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

答案 2 :(得分: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);

在上面的例子中{和}是标签,在它们之间,字符串被提取。