What is the recommended method in PHP to extract the title from a webpage string?

To extract the title from a webpage string in PHP, you can use regular expressions to search for the <title> tag and extract the content within it. This can be achieved by using the preg_match function with a regex pattern that matches the title tag and captures the title content. Once the title content is extracted, you can then display or use it as needed in your application.

// Sample webpage string
$html = &quot;&lt;html&gt;&lt;head&gt;&lt;title&gt;Example Page&lt;/title&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;Hello World&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;&quot;;

// Extract title from webpage string
if (preg_match(&quot;/&lt;title&gt;(.*?)&lt;\/title&gt;/i&quot;, $html, $matches)) {
    $title = $matches[1];
    echo &quot;Title: &quot; . $title;
} else {
    echo &quot;Title not found&quot;;
}