What are some possible ways to extract a filename from a text string in PHP?

When working with text strings in PHP, you may need to extract a filename from a given string. One way to achieve this is by using regular expressions to search for patterns that resemble filenames. By using regex, you can easily identify and extract filenames from text strings.

$string = "This is a sample text with a filename example.txt within it.";
$pattern = "/[a-zA-Z0-9]+\.[a-zA-Z]{3}/"; // Regular expression pattern to match filenames
preg_match($pattern, $string, $matches); // Search for the pattern in the string

$filename = $matches[0]; // Extract the filename from the matched pattern
echo $filename; // Output the extracted filename