How can one efficiently extract specific data elements from a string in PHP?

To efficiently extract specific data elements from a string in PHP, you can use regular expressions. Regular expressions allow you to define patterns to match specific parts of the string and extract the desired data. By using functions like preg_match() or preg_match_all(), you can easily extract the data elements based on the defined pattern.

$string = "Hello, my email is john.doe@example.com and my phone number is 123-456-7890";
$email_pattern = '/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/';
$phone_pattern = '/\d{3}-\d{3}-\d{4}/';

preg_match($email_pattern, $string, $email_matches);
preg_match($phone_pattern, $string, $phone_matches);

$email = $email_matches[0];
$phone = $phone_matches[0];

echo "Email: $email\n";
echo "Phone: $phone\n";