Search code examples
phppreg-match

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

Solution

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