What is the purpose of using regex in PHP for extracting paths from a text file?

When extracting paths from a text file in PHP, using regular expressions (regex) can help to efficiently identify and extract the paths from the text. This is useful when dealing with file paths embedded within a larger text file, as regex allows for pattern matching and extraction of specific strings that match a certain format (such as file paths). By using regex, you can easily extract and work with file paths in PHP.

<?php
$text = "This is a sample text with file paths like /path/to/file1.txt and /another/path/to/file2.txt embedded within it.";
$pattern = '/\/\w+(\/\w+)+\.\w+/'; // regex pattern to match file paths

preg_match_all($pattern, $text, $matches);

$paths = $matches[0];

foreach ($paths as $path) {
    echo "File path: $path\n";
}
?>