What are the advantages and disadvantages of using regex versus string manipulation functions in PHP for text file processing?
When processing text files in PHP, using regular expressions (regex) can provide a more powerful and flexible way to search for and manipulate text patterns. Regex allows for complex pattern matching and substitutions, making it ideal for tasks such as extracting specific data or formatting text. On the other hand, string manipulation functions in PHP can be simpler and more intuitive for basic text processing tasks, making them easier to use for beginners or for simple tasks where regex is not necessary.
// Using regex to extract email addresses from a text file
$text = file_get_contents('sample.txt');
$pattern = '/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/';
preg_match_all($pattern, $text, $matches);
$emails = $matches[0];
foreach($emails as $email) {
echo $email . "\n";
}