Mokus
Mokus

Reputation: 10410

Get text between two tags

How can I get the value from the following tags:

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

The number in the {desc=1} is changing. I want to get the value as well.

UPDATED:

also possible to be more desc in the string, for example

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

Upvotes: 1

Views: 2760

Answers (3)

MichaelCalvin
MichaelCalvin

Reputation: 163

Another very simple way is we can create a simple function that can be invoked at any time.

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

and here's an example usage for your question

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

For more detail please read http://codetutorial.com/howto/how-to-get-of-everything-string-between-two-tag-or-two-strings.

Upvotes: 1

Ravi Verma
Ravi Verma

Reputation: 225

try this

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

in above example { and } are the tags, in-between them the string is getting extracted.

Upvotes: 0

Dogbert
Dogbert

Reputation: 222438

This will capture everything you want.

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

Upvotes: 5

Related Questions