Search code examples
phpregexhtml-parsingpreg-match

PHP - How Get text before tag By preg_match?


How can I get ("TEXT") by preg_match

$Text ='<input value="AAA" name="A1"> <input value="BBB" name="A2"> <input value="TEXT" name="A3">';

preg_match('!<input value="(.*?)" name="A3">!', $Text, $Word);

echo $Word[1];  //AAA" name="A1"> <input value="BBB" name="A2"> <input value="TEXT

Image:

enter image description here


Solution

  • You need to change the .*? part into a negated character class.

    "([^"]*)"
    

    However, you can utilize DOM to achieve this as well.

    $doc = DOMDocument::loadHTML('
         <input value="AAA" name="A1">
         <input value="BBB" name="A2">
         <input value="TEXT" name="A3">
    ');
    
    $xpath = new DOMXPath($doc);
    $match = $xpath->query('//input[@name="A3"]');
    
    echo $match->item(0)->getAttribute('value');