In the realm of PHP, regular expressions play a crucial role in manipulating and extracting information from strings. Among the arsenal of PHP functions designed for this purpose, preg functions stand out.
In this article, we will delve into the functionalities of two essential preg PHP functions: preg_match and preg_replace. Let’s explore their applications with practical examples.
Understanding preg PHP Functions
The `preg_match` function in PHP allows us to perform regular expression matches. It follows a simple syntax: `preg_match(pattern, input string, variable to save results)`. Now, let’s look at some examples to grasp its utility.
Example: Finding a Word in a String
Consider the scenario of locating the word “dogs” in a string. The use of word boundaries (`\b`) and the case-insensitive modifier (`i`) ensures accurate matches.
$str = 'She had stood between the pack of wild dogs and what they wanted';
if (preg_match('/\bdogs\b/i', $str)) {
echo 'Word dogs was found';
} else {
echo 'Word dogs was not found';
}
Example: Extracting Domain from a URL
Here, we demonstrate extracting the domain name from a URL using capturing sub-patterns and non-capturing parenthesized sub-patterns.
$url = 'https://developer.hyvor.com/tutorials';
preg_match('#^(?:\w+://)?([^/]+)#i', $url, $matches);
echo $matches[1];
Example: Using Named Subpatterns
Utilizing named sub-patterns enhances readability and organization when extracting information. Here, we extract book details with named subpatterns.
$str = 'Adventures of Huckleberry Finn: Mark Twain - 1884';
preg_match('/(?P<book>[\w\s]+): (?P<author>[\w\s]+) - (?P<year>\d+)/', $str, $matches);
echo 'Book: ' . $matches['book'] . '<br>';
echo 'Author: ' . $matches['author'] . '<br>';
echo 'Year: ' . $matches['year'];
Boost class loading efficiency with PHP Namespaces Autoload for seamless and organized code structure.
preg_replace Function
The `preg_replace` function not only performs regular expression matches but also facilitates replacements. Its syntax is straightforward: `preg_replace(pattern, replace with, input string)`.
Example: Replacing Digits in a String
In this example, we replace all digits in a string with dollar signs.
$str = 'October 22, 2000';
echo preg_replace('/\d/', '$', $str);
Conclusion
Mastering preg PHP functions opens a gateway to powerful string manipulation and extraction capabilities. The examples provided illustrate the practical applications of `preg_match` and `preg_replace` in various scenarios.
As you delve into PHP forms and beyond, these functions will prove invaluable for handling and processing textual data with efficiency and precision.