How can regular expressions be used to extract variables from HTML code in PHP?

Regular expressions can be used in PHP to extract variables from HTML code by searching for specific patterns or tags within the HTML code. You can use functions like preg_match() or preg_match_all() to match and extract the desired variables based on a regular expression pattern. By defining a regular expression pattern that matches the variable you want to extract, you can then use PHP's regular expression functions to retrieve and store the variable values.

$html = '<div class="content">Hello, <span class="name">John</span></div>';

// Define the regular expression pattern to extract the name variable
$pattern = '/<span class="name">(.*?)<\/span>/';

// Use preg_match() to extract the variable from the HTML code
if (preg_match($pattern, $html, $matches)) {
    $name = $matches[1]; // Extracted variable value
    echo "Name: " . $name; // Output the extracted variable value
} else {
    echo "Variable not found";
}