Content · Programming · PHP

PHP fnmatch() Function: Usage and Examples

Understand PHP fnmatch() with three examples, return behavior, important pitfalls, and related operations.

2 views Published Oct 16, 2026 Updated Oct 16, 2026

Use fnmatch() when you need to checks whether a filename-like string matches a wildcard pattern in a PHP application. The examples below show the actual operation and its limitations.

What Is fnmatch() in PHP?

Checks whether a filename-like string matches a wildcard pattern. The exact signature supported by your installation depends on its PHP version and enabled extensions.

Its syntax is:

fnmatch(string $pattern, string $filename, int $flags = ...): bool

Parameters and return value: The parameter types, optional arguments, references, and return type are shown in the signature above. Optional parameters are marked with an ellipsis in this reference signature.

Example 1: Basic Usage

<?php

var_dump(fnmatch("*.txt", "notes.txt"));

Output:

bool(true)

Example 2: Different Input or Behavior

<?php

var_dump(fnmatch("report?.csv", "report2.csv"));

Output:

bool(true)

Practical Example: Applying the Function

<?php

$files = ["photo.jpg", "report.csv", "data.csv"]; foreach ($files as $file) { if (fnmatch("*.csv", $file)) echo $file . PHP_EOL; }

Output:

report.csv
data.csv

Important Behavior and Edge Cases

Wildcards are not regular expressions; slash and case behavior can depend on flags and platform.

Comparison With Related Functions

ApproachDifference
fnmatch()Checks whether a filename-like string matches a wildcard pattern.
Related operationpreg_match() uses regular expressions; fnmatch() uses shell-style wildcard patterns.

Common Beginner Mistakes

MistakeCorrect Approach
Ignoring the function-specific limitationWildcards are not regular expressions; slash and case behavior can depend on flags and platform.
Confusing this function with a related operationpreg_match() uses regular expressions; fnmatch() uses shell-style wildcard patterns.

Key Takeaways

  • Checks whether a filename-like string matches a wildcard pattern.
  • Wildcards are not regular expressions; slash and case behavior can depend on flags and platform.
  • preg_match() uses regular expressions; fnmatch() uses shell-style wildcard patterns.

Use fnmatch() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.

Share this resourceSend this page to someone who may find it useful.