PHP Regular Expression Common Functions
- 2021-07-13 04:37:38
- OfStack
1. preg_match ()
Function prototype: int preg_match (string $pattern, string $content [, array $matches])
The preg_match () function searches the $content string for a match to the regular expression given by $pattern. If $matches is provided, the matching result is put in it. $matches [0] will contain the text that matches the entire pattern, $matches [1] will contain the first captured content that matches the pattern unit in parentheses, and so on. This function only matches once, and finally returns the number of matching results of 0 or 1. Code 6.1 gives a code example of the preg_match () function.
Code 6.1 Matching of date and time
The code is as follows:
<?php
// A matching string is required. date Function returns the current time
$content = "Current date and time is ".date("Y-m-d h:i a").", we are learning PHP together.";
// Use the usual method to match time
if (preg_match ("//d{4}-/d{2}-/d{2} /d{2}:/d{2} [ap]m/", $content, $m))
{
echo " The matching time is: " .$m[0]. "/n";
}
// Because the pattern of time is obvious, it can also be easily matched
if (preg_match ("/([/d-]{10}) ([/d:]{5} [ap]m)/", $content, $m))
{
echo " The current date is: " .$m[1]. "/n";
echo " The current time is: " .$m[2]. "/n";
}
?>
This is a simple example of dynamic text string matching. Assuming the current system time is "August 17, 2006, 13:25," the output is as follows.
Matching time: 2006-08-17 01:25 pm
Current date is: 2006-08-17
Current time is: 01:25 pm
2. ereg () and eregi ()
ereg () is a matching function for regular expressions in the POSIX extension library. eregi () is a case-ignorant version of the ereg () function. The function of preg_match is similar to that of preg_match, but the function returns a Boolean value indicating whether the match was successful or not. It should be noted that the first parameter of the POSIX extension library function accepts a regular expression string, that is, there is no need to use a delimiter. For example, code 6.2 is a method for file name security verification.
Code 6.2 File name security check
The code is as follows:
<?php
$username = $_SERVER['REMOTE_USER'];
$filename = $_GET['file'];
// Filter the file name to ensure the system security
if (!ereg('^[^./][^/]*$', $userfile))
{
die(' This is not 1 Illegal filename! ');
}
// Filtering User Names
if (!ereg('^[^./][^/]*$', $username))
{
die(' This is not 1 Invalid username ');
}
// Split file paths through security filtering
$thefile = "/home/$username/$filename";
?>
Typically, using the Perl-compatible regular expression matching function perg_match () will be faster than using ereg () or eregi (). The strstr () or strpos () functions are recommended if you are simply looking for a substring in a string.
Substitution of regular expressions
1. ereg_replace () and eregi_replace ()
Function prototype: string ereg_replace (string $pattern, string $replacement, string $string)
string eregi_replace (string $pattern, string $replacement, string $string)
ereg_replace () searches for the pattern string $pattern in $string and replaces the matching result with $replacement. When a pattern unit (or sub-pattern) is included in $pattern, positions in the shape of "/1" or "$1" in $replacement will be replaced in turn by what these sub-patterns match. And "/0" or "$0" refers to the contents of the whole matching string. It should be noted that backslashes are used as escape characters in double quotation marks, so the forms of "//0" and "//1" must be used.
eregi_replace () and ereg_replace () have 1 function, except that the former ignores case. Code 6.6 is an application example of this function, this code demonstrates how to do a simple clean-up of the program source code.
Code 6.6 Cleanup of source code
The code is as follows:
<?php
$lines = file('source.php'); // Read a file into an array
for($i=0; $i<count($lines); $i++)
{
// End the line with " // "Or" # Remove the commentary at the beginning of "
$lines[$i] = eregi_replace("(////|#).*$", "", $lines[$i]);
// Eliminate the white space at the end of the line
$lines[$i] = eregi_replace("[ /n/r/t/v/f]*$", "/r/n", $lines[$i]);
}
// After finishing, output to the page
echo htmlspecialchars(join("",$lines));
?>
2. preg_replace ()
Function prototype: mixed preg_replace (mixed $pattern, mixed $replacement, mixed $subject [, int $limit])
preg_replace is more powerful than ereg_replace. Arrays can be used for the first three parameters; The fourth parameter, $limit, can set the number of replacements, which defaults to all replacements. Code 6.7 is an application example of array substitution.
Code 6.7 Array Replacement
The code is as follows:
<?php
// String
$string = "Name: {Name}<br>/nEmail: {Email}<br>/nAddress: {Address}<br>/n";
// Mode
$patterns =array(
"/{Address}/",
"/{Name}/",
"/{Email}/"
);
// Replace string
$replacements = array (
"No.5, Wilson St., New York, U.S.A",
"Thomas Ching",
"tom@emailaddress.com",
);
// Output mode replacement results
print preg_replace($patterns, $replacements, $string);
?>
The output is as follows.
Name: Thomas Ching",
Email: tom@emailaddress.com
Address: No.5, Wilson St., New York, U.S.A
The pattern modifier "e" can be used in the regular expression of preg_replace. Its function is to use the matching result as an expression and can be recalculated. For example:
The code is as follows:
<?php
$html_body = " <HTML><Body><H1>TEST</H1>My Picture<Img src= " my.gif " ></Body></HTML> " ;
// In the output result HTML Labels will be all lowercase letters
echo preg_replace (
"/(<//?)(/w+)([^>]*>)/e",
"'//1'.strtolower('//2').'//3'", // Pattern variables here //2 Will be strtolower Convert to lowercase characters
$html_body);
?>
Prompt
The preg_replace function uses the Perl compliant regular expression syntax and is generally a faster alternative to ereg_replace. If you are simply substituting strings, you can use the str_replace function.