簡體   English   中英

獲取兩個標簽之間的文本

[英]Get text between two tags

如何從以下標簽中獲取值:

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

{desc=1}中的數字正在改變。 我也想獲得價值。

更新:

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

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

這將捕獲您想要的一切。

$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);

Output:

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
"
  }
}

另一個非常簡單的方法是我們可以創建一個可以隨時調用的簡單 function。

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

嘗試這個

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

在上面的例子中 { 和 } 是標簽,在它們之間,字符串被提取出來。

暫無
暫無

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

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