How can PHP be used to extract and manipulate specific elements within a string based on a predefined pattern?

To extract and manipulate specific elements within a string based on a predefined pattern in PHP, you can use regular expressions. Regular expressions allow you to define a pattern and then search for or manipulate text that matches that pattern within a string. PHP provides built-in functions like preg_match() and preg_replace() to work with regular expressions and achieve this task.

<?php
$string = "Hello, my email is example@email.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 = '/[0-9]{3}-[0-9]{3}-[0-9]{4}/';

// Extract email
preg_match($email_pattern, $string, $email_matches);
$email = $email_matches[0];
echo "Email: $email\n";

// Extract phone number
preg_match($phone_pattern, $string, $phone_matches);
$phone = $phone_matches[0];
echo "Phone: $phone\n";

// Replace phone number
$replacement = '555-555-5555';
$new_string = preg_replace($phone_pattern, $replacement, $string);
echo "New String: $new_string\n";
?>