Search code examples
phpregexpreg-match

Preg match few times in same file


<b>Text 1</b><br><i>Text 2</i>

Some text - very long and not interesting.

<b>Text 3</b><br><i>Text 4</i>

How could I take text 1, text 2, text 3 and text 4 in one go when using preg match function?


Solution

  • Just try with:

    $input = '<b>Text 1</b><br><i>Text 2</i>
              Some text - very long and not interesting.
              <b>Text 3</b><br><i>Text 4</i>';
    $dom = new DOMDocument();
    $dom->loadHTML($input);
    $xpath = new DOMXpath($dom);
    $items = $xpath->query('//i | //b');
    
    $output = [];
    foreach ($items as $item) {
        $output[] = $item->textContent;
    }
    
    var_dump($output);
    

    Output:

    array (size=4)
      0 => string 'Text 1' (length=6)
      1 => string 'Text 2' (length=6)
      2 => string 'Text 3' (length=6)
      3 => string 'Text 4' (length=6)