1

I want to read all tag attributes with the word title, HTML sample below

<html>
    <head>
        <title> </title>
    </head>
    <body>
        <div title="abc"> </div>
        <div> 
            <span title="abcd"> </span>
        </div>
        <input type="text" title="abcde">
    </body>
</html>

I have tried this regex function, which doesn't work

preg_match('\btitle="\S*?"\b', $html, $matches);
2
  • You would be better off using DOMDocument rather than try and hack it with regexs. Commented Dec 12, 2019 at 7:35
  • /title="(.*)"/g Commented Dec 12, 2019 at 7:43

2 Answers 2

2

Just to follow up on my comment, using regex's isn't particularly safe or robust enough to manage HTML (although with some HTML - there is little hope of anything working fully) - have a read of https://stackoverflow.com/a/1732454/1213708.

Using DOMDocument provides a more reliable method, to do the processing you are after you can use XPath and search for any title attributes using //@title (the @ sign is the XPath notation for attribute).

$html = '<html>
<head>
   <title> </title>
</head>
 <body>
   <div title="abc"> </div>
   <div> 
           <span title="abcd"> </span>
   </div>
       <input type="text" title="abcde">
</body>
</html>';

$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html);

$xpath = new DOMXPath($doc);

foreach($xpath->query('//@title') as $link) {
    echo $link->textContent.PHP_EOL;
}

which outputs...

abc
abcd
abcde
Sign up to request clarification or add additional context in comments.

1 Comment

thank you , it worked perfect, i have accepted this as a solution.
0

Here's a regex solution

preg_match_all('~\s+title\s*=\s*["\'](?P<title>[^"]*?)["\']~', $html, $matches);
$matches = array_pop($matches);
foreach($matches as $m){
    echo $m . " ";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.