How can one optimize PHP code that uses preg_match() to accurately extract specific data from a string while avoiding extraneous results?
When using preg_match() to extract specific data from a string in PHP, it's important to craft a precise regular expression pattern to accurately target the desired data while avoiding extraneous results. To optimize the code, ensure the regular expression is tailored to match only the exact data you need by using anchors like ^ (start of string) and $ (end of string) and specific patterns to match the desired data.
// Example code snippet to extract a specific pattern (e.g., phone numbers) from a string
$string = "Contact us at 123-456-7890 or 555-5555-5555 for assistance.";
$pattern = '/\b\d{3}-\d{3}-\d{4}\b/';
preg_match($pattern, $string, $matches);
echo "Phone number: " . $matches[0];
Related questions
-
ssh_exec ssh2_exec PHP
-
PHP code structure code formatting
-
PHP URL page name