When dealing with variable data formats in PHP, such as names with or without additional titles, how can regular expressions (regex) be used to efficiently extract desired information?

When dealing with variable data formats in PHP, regular expressions can be used to efficiently extract desired information by defining patterns that match the different formats. For example, if we want to extract names with or without additional titles like "Mr." or "Mrs.", we can use regex to capture both cases. By using regex, we can create a flexible solution that can handle various data formats and extract the desired information accurately.

$name = "Mr. John Doe";

// Define a regex pattern to match names with or without titles
$pattern = '/(Mr\.|Mrs\.|Ms\.)?\s*(\w+)\s*(\w+)/';

// Use preg_match to extract the title, first name, and last name
preg_match($pattern, $name, $matches);

$title = $matches[1];
$first_name = $matches[2];
$last_name = $matches[3];

echo "Title: $title\n";
echo "First Name: $first_name\n";
echo "Last Name: $last_name\n";