


Detailed explanation of strings and regular expressions in php, detailed explanation of php regular expressions_PHP tutorial
Detailed explanation of strings and regular expressions in php, detailed explanation of php regular expressions
1. Characteristics of string type
1. PHP is a weakly typed language, and other data types can generally be directly applied to string function operations.
<?php<br />echo substr("123456",2,4); //输出345<br />echo substr(123456,2,4); //输出345<br />echo hello; //先查找hello常量,若没找到,将hello看做字符串使用<br />?>
2. Strings can be used as "arrays", which are collections of characters.
<?php<br />$str = "www.jb51.net";<br />echo $str[0];<br />echo $str[1];<br />echo $str[2];<br />?>
But strings are not real arrays, and array functions cannot be used. For example, count($str) will not return the length of the string. The PHP engine cannot distinguish between characters and arrays, causing ambiguity. Since PHP 4, curly braces have been used instead of square brackets.
<?php<br />//为保证向后兼容,方括号仍然可以使用<br />$str = www.jb51.net;<br />echo $str{0};<br />echo $str{1};<br />echo $str{2};<br />?>
3. Double quote variable analysis
In PHP, when a string is defined with double quotes or delimiters, the variables in it will be parsed.
<?php<br />$arr = array('name' => "dwqs",'add' => "www.ido321.com");<br>echo "$arr[name]"; //可以解析,但是在方括号中不能使用引号<br>//echo "$arr['name']"; 错误<br>echo "{$arr['name']}"; //可以解析,用花括号包含元素,name不带引号也是可以的<br>//假设存在对象$square<br>echo "$square->width"; //可以解析<br>echo "$square->width00 cent"; //不可以解析,用花括号解决<br>echo "{$square->width}width00 cent"; //可以解析<br>?>
2. String output function
3. Commonly used string format functions
PS: Most of PHP’s string processing functions do not modify the source string, but return a new string
4. Regular expressions
Regular expression describes a string matching pattern, through which strings are matched, searched, replaced and separated in specific functions. It consists of three parts: atoms, metacharacters and pattern modifiers. text mode.
In PHP, there are two sets of regular processing function libraries: PCRE and POSIX. The former is named with preg_ prefix and is compatible with Perl; the latter is named with ereg_ prefix. The functions of the two are similar, but the efficiency of PCRE is slightly higher.
Regular expression processing function compatible with Perl language:
1. Grammar
1.1 Delimiter: When using a pattern in a Perl-compatible regular function, you must add a delimiter to the pattern. Any character except letters, numbers and backslash () can be used as a delimiter
<?php<br />//以下正则合法<br />echo $m1 = '/<\/\w+/';<br />echo $m2 = '|(\d{3})-\d|Sm';<br />echo $m3 = '!^(?i)php[34]!';<br />echo $m4 = '{^\s+(\s+)?$}';<br />?>
1.2 Atoms: Atoms include ordinary characters, such as letters and numbers; non-printing characters, such as spaces and carriage returns; special characters and metacharacters, such as quotation marks, *, +, etc., which must be escaped with ""; self Define atomic tables, such as [apj], [a-z]; general character types, such as d, D.
<?php<br />//下面二者等价,匹配e-mail<br />$mail1 = '/^[0-9a-zA-Z]+@[0-9a-zA-Z]+(\.[0-9a-zA-Z]+){0,3}$/';<br />$mail2 = '/^\w+@\w+(\.\w+){0,3}$/';<br />?>
1.3 Metacharacters: Characters with special meanings used to build regular expressions. Perl can use various metacharacters to search for matches, such as *, +, ? .Common metacharacters are as follows
1.4 Pattern modifier: Used in addition to regular delimiters to extend regular functions in matching, replacement, etc.
2. Regular expression function compatible with Perl
2.1 preg_match(string pattern,string subject[,array matches]): used to search and match strings. Parameter description:
pattern is a regular pattern, subject is a string that needs to be processed, optional matches are used to save the matching results of each sub-pattern of pattern, matches[0] saves the overall content matching pattern, matches[1] saves The matched content in the first parentheses of pattern, and so on.
<?php<br />header("content-type:text/html;charset=utf8");<br />$pattern = '/(http):\/\/(www)\.([^\.\/]+)\.(com|net|org)/i';<br />$subject = "我的博客:http://www.ido321.com";<br />if(preg_match($pattern, $subject,$matches)){<br />echo "搜索的URL是:".$matches[0]."<br/>"; //数组第1个元素保存整个匹配结果<br>echo "URL中的协议是:".$matches[1]."<br/>";//数组第2个元素保存第1个字表达式<br>echo "URL中的主机是:".$matches[2]."<br/>";//数组第3个元素保存第2个字表达式<br>echo "URL中的域名是:".$matches[3]."<br/>";//数组第4个元素保存第3个字表达式<br>echo "URL中的顶域是:".$matches[4]."<br/>";//数组第5个元素保存第4个字表达式<br>}<br>?>
Results
preg_match_all() is similar to the preg_match() function, except that the former will match until the end of the string, while the latter will stop matching after the first match.
2.2 preg_grep(string pattern, array iput): Match the elements in the array and return the array unit that matches the regular pattern. Parameter description:
pattern is a regular pattern, and input is an array that needs to be matched.
<?php<br />$arr = array('Linux RedHat9.0','Apache2.2.9','MySQL5.0.51','PHP5.2.6','LAMP','100');<br />$version = preg_grep('/^[a-zA-Z]+(\d|\.)+$/',$arr);<br />//输出:Array([1]=>Apache2.2.9 [2]=>MySQL5.0.51 [3]=>PHP5.2.6)<br>print_r($version); <br>?>
2.3 preg_replace(mixed pattern, mixed replacement, mixed subject[,int limit]): String replacement. Description:
This function will search for a match with pattern in the subject and replace it with replacement. Limit is used to limit the number of matches, that is, the number of substitutions.
<?php<br />$pattern = '/<[\/\!]*?[^<>]*?/is';<br>$text = '这个文本有<b>粗体</b>和<u>带有下划线</u>以及<i>斜体</i>';<br>echo preg_replace($pattern,"",$text); //将所有HTML标记替换为空<br>echo preg_replace($pattern,"",$text,2); //值替换前2个HTML标记<br>?>
2.4 preg_split(string pattern,string subject[,int limit[,int flags]]): Split the string. Description:
The function returns an array. The array elements contain strings in the subject divided by boundaries that match pattern. For the meaning of limit, see 2.3. For the meaning of flags, please refer to the documentation.
<?php<br />//按任数量的空格分割字符串<br />$kerwords = preg_split("/[\s,]+/","hypertext language,programming");<br />//输出:Array([0]=>hypertext [1]=>language,[2[=>programming)<br>print_r($kerwords);<br>?>
$str='{"a":1234567890,"b":"u","birthday":"2000-01-01","gender":"1","location ":"123456","login_ip":"123.123.123.123","login_time":1234567890,"id":"1234567","sign":"0bcbdea54d1f2c3c75b058eb5d2ae124"}';
$user_id="";
if (preg_match_all('|"id":"(\S+?)"|', $str, $reg))
{
$user_id=$reg[1][0];
}
echo "UserID is : ".$user_id;
?>
Output result:
UserID is : 1234567
You can use regular expressions or php directly. I feel that php is more convenient:
$str = str_replace("","

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
