


Analogy of the two main functions of regular expressions in POSIX style and compatible Perl style (preg_match, preg_replace,_PHP tutorial
First, let’s take a look at the two main functions of POSIX-style regular expressions:
ereg function: (regular expression matching)
Format: int ereg ( string pattern, string string [, array ®s ] )
Note: The preg_match() function using Perl-compatible regular expression syntax is often a faster alternative to ereg(). (Generally speaking, it is better to use preg_match(), which is better~~)
Find the substring in string that matches the given regular expression pattern in a case-sensitive manner. If a substring is found that matches a subpattern enclosed in parentheses in pattern and the function call is given a third argument, regs, the match will be stored in the regs array. $regs[1] contains the substring starting with the first left parenthesis, $regs[2] contains the second substring, and so on. $regs[0] contains the entire matched string.
Return value: If a match of the pattern pattern is found in string, the length of the matched string is returned. If no match is found or an error occurs, FALSE is returned. If the optional parameter regs is not passed in or the length of the matched string is 0, this function returns 1.
Let’s take a look at an example of the ereg() function:
The following code snippet accepts a date in ISO format (YYYY-MM-DD) and displays it in DD.MM.YYYY format:
if (ereg ("([0-9]{4} )-([0-9]{1,2})-([0-9]{1,2})", $date, $regs)) {
echo "$regs[3].$regs [2].$regs[1]";
} else {
echo "Invalid date format: $date";
}
?>
- -------------------------------------------------- --------------------------------
ereg_replace function: (regular expression replacement)
Format: string ereg_replace (string pattern, string replacement, string string)
Function description:
This function scans the part matching pattern in string and replaces it with replacement.
Returns the replaced string. (If there is no match for replacement, the original string will be returned.)
If pattern contains substrings in brackets, replacement can contain substrings of the form \digit, and these substrings will be replaced with numbers. represents the substring within the parentheses; \0 contains the entire content of the string. Up to nine substrings can be used. Parentheses can be nested, in which case the left parenthesis is used to calculate the order.
If no match is found in string, string will be returned unchanged.
Let’s take a look at this function example:
1. The following code snippet outputs "This was a test" three times:
$string = "This is a test";
echo str_replace(" is", " was", $string);
echo ereg_replace("( )is", "\1was", $string);
echo ereg_replace("(( )is)", "\2was", $string);
?>
One thing to note is that if you use an integer value in the replacement parameter, you may not get the expected results. This is because ereg_replace() will interpret and apply numbers as sequence values of characters. For example:
2, example when the replacement parameter is an integer:
php
/* cannot produce the expected results*/
$num = 4;
$string = "This string has four words.";
$string = ereg_replace('four', $ num, $string);
echo $string; /* Output: 'This string has words.' */
/* This example works fine*/
$num = '4';
$string = "This string has four words.";
$string = ereg_replace('four', $num, $string);
echo $string; /* Output: 'This string has 4 words.' */
?>
3, replace the URL with a hyperlink:
"< ;a href="\0">\0", $text);
Tip: The preg_replace() function uses Perl-compatible regular expression syntax and is often a faster alternative to ereg_replace().
Let’s take a look at the two main functions of Perl that are compatible with regular expressions:
preg_match function: (regular expression matching)
Format: int preg_match ( string pattern, string subject [, array matches [, int flags]] )
Function description:
Search for content matching the regular expression given by pattern in the subject string.
If matches is provided, it will be populated with the results of the search. $matches[0] will contain text that matches the entire pattern, $matches[1] will contain text that matches the first captured subpattern in parentheses, and so on.
flags can be the following flags:
PREG_OFFSET_CAPTURE
If this flag is set, the associated string offset of each occurrence of the matching result will also be returned. Note that this changes the value of the returned array so that each cell in it is also an array, where the first item is the matched string and the second item is its offset. This tag is available since PHP 4.3.0.
flags parameter is available since PHP 4.3.0.
preg_match() returns the number of times pattern is matched. Either 0 times (no match) or 1 time, since preg_match() will stop searching after the first match. preg_match_all(), on the contrary, will search until the end of subject. If an error occurs preg_match() returns FALSE.
Tips: If you just want to check whether a string is contained in another string, don't use preg_match(). You can use strpos() or strstr() instead, which is much faster.
Let’s take a look at its example:
Example 1. Search for "php" in text:
// The "i" after the pattern delimiter indicates a case-insensitive search
if (preg_match ("/php/i", "PHP is the web scripting language of choice.")) {
print "A match was found.";
} else {
print "A match was not found.";
}
? >
Example 2. Search for the word "web":
/* The b in the pattern represents the word boundary, so only the independent word "web" will be matched,
* will not match the words such as "webbing" or "cobweb" part*/
if (preg_match ("/bwebb/i", "PHP is the web scripting language of choice.")) {
print "A match was found.";
} else {
print "A match was not found.";
}
if (preg_match ("/bwebb/i", "PHP is the website scripting language of choice.")) {
print "A match was found.";
} else {
print "A match was not found.";
}
?>
Example 3. From URL Get the domain name:
// Get the host name from the URL
preg_match("/^(http://)?([^/]+)/i",
"http://www.php.net/index.html", $matches);
$host = $matches[2];
// Get the next two segments from the host name
preg_match("/[^./]+.[^./]+$/", $host , $matches);
echo "domain name is: {$matches[0]}n";
?>
This example will output:
domain name is : php.net
---------------------------------------------- -------------------------------------
preg_replace function: (execute regular expression (formula search and replacement)
Format: mixed preg_replace (mixed pattern, mixed replacement, mixed subject [, int limit])
Function description:
Search for a match of pattern pattern in subject and replace it with replacement . If limit is specified, only limit matches are replaced; if limit is omitted or has a value of -1, all matches are replaced.
replacement can contain backreferences in the form \n or (since PHP 4.0.4) in the form $n, the latter being preferred. Each such reference will be replaced by text matching the nth captured bracketed subpattern. n can be from 0 to 99, where \0 or $0 refers to the text matched by the entire pattern. Count the left parentheses from left to right (starting at 1) to get the number of subpatterns.
For replacement patterns that follow a backreference by a number (i.e. a number that immediately follows a matching pattern), the familiar \1 notation cannot be used to represent the backreference. For example, \11 will make preg_replace() confused whether it wants a backreference of \1 followed by the number 1 or a backreference of \11. The solution in this case is to use ${1}1. This creates an isolated backreference for $1, leaving the other 1 as a mere literal.
Let’s take a look at its example:
Example 1. The usage of reverse reference followed by a number:
$string = "April 15, 2003";
$pattern = "/(w+) (d+), (d+)/i";
$replacement = "${1}1,$3";
print preg_replace($pattern, $replacement, $string);
/* Output
======
April1,2003
*/
?>
If a match is found, the replaced subject will be returned, otherwise the original unchanged subject will be returned.
Each parameter of preg_replace() (except limit) can be an array. If both pattern and replacement are arrays, their keys will be processed in the order in which they appear in the array. This is not necessarily the same as the numerical order of the index. If an index is used to identify which pattern is to be replaced by which replacement, the array should be sorted with ksort() before calling preg_replace().
Example 2. Using index array in preg_replace():
php
$string = "The quick brown fox jumped over the lazy dog.";
$patterns[0] = "/quick/";
$patterns[1] = "/brown/";
$patterns[2] = "/fox/";
$replacements[2] = "bear";
$replacements[1] = "black";
$replacements[0] = "slow";
print preg_replace($patterns, $replacements, $string);
/* Output
======
The bear black slow jumped over the lazy dog.
*/
/* By ksorting patterns and replacements,
we should get what we wanted. */
ksort($patterns);
ksort($replacements);
print preg_replace( $patterns, $replacements, $string);
/* Output
======
The slow black bear jumped over the lazy dog.
*/
?>
If subject is an array, a search and replace is performed on each item in subject and an array is returned.
If pattern and replacement are both arrays, preg_replace() will take out values from them in order to search and replace subject. If there are fewer values in replacement than in pattern, the empty string is used as the remaining replacement value. If pattern is an array and replacement is a string, this string is used as the replacement value for each value in pattern. The other way around is meaningless. The
/e modifier causes preg_replace() to treat the replacement argument as PHP code (after the appropriate backreferences have been replaced). Tip: Make sure that replacement forms a valid PHP code string, otherwise PHP will report a syntax parsing error on the line containing preg_replace().
Example 3. Replace several values:
$patterns = array ("/(19|20)(d{2})-(d{1,2})-(d{1,2})/",
"/^s*{(w+ )}s*=/");
$replace = array ("\3/\4/\1\2", "$\1 =");
print preg_replace ($patterns, $replace, "{startDate} = 1999-5-27");
?>
This example will output:
$startDate = 5/27/1999
Example 4. Use /e modifier:
preg_replace ("/( ?)(w+)([^>]*>)/e",
"'\1'.strtoupper('\2').'\3'",
$html_body );
?>
This will make all HTML tags in the input string uppercase.
Example 5. Convert HTML to text:
// $document should contain an HTML document.
// This example will remove HTML tags, javascript code
// and whitespace characters. Also converts some common
// HTML entities into corresponding text.
$search = array ("'<script>]*?>.*?</script>'si", // Remove javascript
"']*?>'si", // Remove HTML tags
"'([rn])[s]+'", // Remove whitespace characters
"'&( quot|#34);'i", // Replace HTML entity
"'&(amp|#38);'i",
"'&(lt|#60);'i",
"'&(gt|#62);'i",
"'&(nbsp|#160);'i",
"'&(iexcl|#161);'i",
"'&(cent|#162);'i",
"'&(pound|#163);'i",
"'&(copy|#169);'i" ,
"'(d+);'e"); // Run as PHP code
$replace = array ("",
"",
"\1",
""",
"&",
"">",
" ",
chr(161),
chr(162),
chr(163),
chr(169),
"chr(\1)");
$text = preg_replace ($search, $replace, $document);
? >
The End…

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor