📜  pregmatch - PHP (1)

📅  最后修改于: 2023-12-03 15:18:41.582000             🧑  作者: Mango

preg_match - PHP

preg_match is a PHP function used for performing regular expression match. It is often used for pattern matching but can also be used for text parsing.

Syntax
preg_match($pattern, $subject, &$matches);
  • $pattern: The regular expression pattern to match.
  • $subject: The input string to search for the pattern.
  • $matches: (Optional) An array that will be filled with the matches found in the subject string.
Example 1 - Pattern Matching
$string = "The quick brown fox jumps over the lazy dog.";
$pattern = '/quick/';

if (preg_match($pattern, $string)) {
    echo "Pattern found!";
} else {
    echo "Pattern not found.";
}

The above example searches for the word quick in the string and outputs Pattern found! if the pattern is found.

Example 2 - Text Parsing
$string = "My name is John and I am 30 years old.";
$pattern = '/^My name is (\w+) and I am (\d+) years old\.$/';

if (preg_match($pattern, $string, $matches)) {
    echo "Name: " . $matches[1] . "<br>";
    echo "Age: " . $matches[2];
}

The above example extracts the name and age from the given string using regular expressions. The output of this example would be:

Name: John
Age: 30
Conclusion

preg_match is a powerful function in PHP for pattern matching and text parsing. Understanding how to use regular expressions can greatly enhance your ability to manipulate strings and perform advanced text processing.