Home Backend Development PHP Problem PHP regular expression function

PHP regular expression function

Jun 08, 2020 pm 05:26 PM
php

PHP regular expression function


前面的话

  正则表达式不能独立使用,它只是一种用来定义字符串的规则模式,必须在相应的正则表达式函数中应用,才能实现对字符串的匹配、查找、替换及分割等操作。前面介绍了正则表达式的基础语法,本文将详细介绍正则表达式函数

匹配与查找

【preg_match()】
Copy after login

  preg_match()函数用来执行一个正则表达式匹配,搜索subject与pattern给定的正则表达式的一个匹配。返回pattern的匹配次数。它的值将是0次(不匹配)或1次,因为preg_match()在第一次匹配后将会停止搜索。preg_match_all()不同于此,它会一直搜索subject直到到达结尾。如果发生错误preg_match()返回FALSE

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
Copy after login

  pattern表示要搜索的模式,字符串类型

  subject表示输入字符串

  如果提供了参数matches,它将被填充为搜索结果。$matches[0]将包含完整模式匹配到的文本, $matches[1] 将包含第一个捕获子组匹配到的文本,以此类推

  flags可以被设置为以下标记:1、PREG_OFFSET_CAPTURE。如果传递了这个标记,对于每一个出现的匹配返回时会附加字符串偏移量(相对于目标字符串的)。注意:这会改变填充到matches参数的数组,使其每个元素成为一个由第0个元素是匹配到的字符串,第1个元素是该匹配字符串在目标字符串subject中的偏移量;2、offset。通常,搜索从目标字符串的开始位置开始。可选参数offset用于指定从目标字符串的某个未知开始搜索(单位是字节)

<?php
//从URL中获取主机名称
preg_match(&#39;@^(?:http://)?([^/]+)@i&#39;,    "http://www.php.net/index.html", $matches);
$host = $matches[1];//获取主机名称的后面两部分
preg_match(&#39;/[^.]+.[^.]+$/&#39;, $host, $matches);//domain name is: php.netecho "domain name is: {$matches[0]}";
?>
Copy after login
<?php
 $pattern = &#39;/www.[^./]+.com/i&#39;;
$subject = &#39;www.baidu.com,www.qq.com,www.cnblogs.com&#39;;preg_match($pattern,$subject,$matches);/*array (size=1)  0 => string &#39;www.baidu.com&#39; (length=13) */var_dump($matches);
?>
Copy after login

【preg_match_all()】

  preg_match_all()与preg_match()类似,不同的是preg_match()在第一次匹配之后就会停止搜索,而函数preg_match_all()则会一直搜索到指定字符串的结尾,可以获取到所有匹配到的结果

int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )
Copy after login
<?php 
$pattern = &#39;/www.[^./]+.com/i&#39;;$subject = &#39;www.baidu.com,www.qq.com,www.cnblogs.com&#39;;
preg_match_all($pattern,$subject,$matches);
/*
array (size=1)  0 => 
    array (size=3)      0 => string &#39;www.baidu.com&#39; (length=13)      1 => string &#39;www.qq.com&#39; (length=10)      2 => string &#39;www.cnblogs.com&#39; (length=15)
 */
var_dump($matches);
?>
Copy after login
【preg_grep()】
Copy after login

  preg_grep()返回给定数组input中与模式pattern 匹配的元素组成的数组

array preg_grep ( string $pattern , array $input [, int $flags = 0 ] )

  如果flags设置为PREG_GREP_INVERT,这个函数返回输入数组中与 给定模式pattern不匹配的元素组成的数组

<?php 
$pattern = &#39;/www.[^./]+.com/i&#39;;
$subject = [&#39;baidu.com&#39;,&#39;www.qq.com&#39;,&#39;www.cnblogs.com&#39;];var_dump (preg_grep($pattern,$subject));
?>
Copy after login

替换

【preg_replace()】

 preg_replace()执行一个正则表达式的搜索替换,搜索subject匹配pattern的部分,以replacement进行替换
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
Copy after login

  replacement表示用于替换的字符串或字符串数组。如果这个参数是一个字符串,并且pattern是一个数组,那么所有的模式都使用这个字符串进行替换。如果pattern和replacement都是数组,每个pattern使用replacement中对应的元素进行替换。如果replacement中的元素比pattern中的少,多出来的pattern使用空字符串进行替换

<?php
$string = &#39;April 15, 2016&#39;;$pattern = &#39;/(w+) (d+), (d+)/i&#39;;
$replacement = &#39;${1}1,$3&#39;;//April1,2016echo preg_replace($pattern, $replacement, $string);
?><?php
$string = &#39;The quick brown fox jumped over the lazy dog.&#39;;
$patterns = array();
$patterns[0] = &#39;/quick/&#39;;
$patterns[1] = &#39;/brown/&#39;;
$patterns[2] = &#39;/fox/&#39;;$replacements = array();
$replacements[2] = &#39;bear&#39;;$replacements[1] = &#39;black&#39;;
$replacements[0] = &#39;slow&#39;;//The bear black slow jumped over the lazy dog.echo preg_replace($patterns, $replacements, $string);
?>
Copy after login
【preg_replace_callback()】
Copy after login

  preg_replace_callback()执行一个正则表达式搜索并且使用一个回调进行替换

mixed preg_replace_callback ( mixed $pattern , callable $callback , mixed $subject [, int $limit = -1 [, int &$count ]] )
Copy after login
<?php
// 将文本中的年份增加一年.
$text = "April fools day is 04/01/2002";
$text.= "Last christmas was 12/24/2001";
// 回调函数
function next_year($matches){  // 通常: $matches[0]是完成的匹配  // $matches[1]是第一个捕获子组的匹配  // 以此类推  return $matches[1].($matches[2]+1);}>
Copy after login

【preg_filter()】

  preg_filter() 执行一个正则表达式搜索和替换,等价于preg_replace()除了它仅仅返回(可能经过转化)与目标匹配的结果

mixed preg_filter ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
Copy after login
<?php
$subject = array(&#39;1&#39;, &#39;a&#39;, &#39;2&#39;, &#39;b&#39;, &#39;3&#39;, &#39;A&#39;, &#39;B&#39;, &#39;4&#39;); $pattern = array(&#39;/d/&#39;, &#39;/[a-z]/&#39;, &#39;/[1a]/&#39;); $replace = array(&#39;A:$0&#39;, &#39;B:$0&#39;, &#39;C:$0&#39;); ?>
Copy after login

分割

【preg_split()】
  preg_split()通过一个正则表达式分隔字符串
array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )
Copy after login

  如果指定limit,将限制分隔得到的子串最多只有limit个,返回的最后一个子串将包含所有剩余部分。limit值为-1,0或null时都代表"不限制";可以使用null跳过对flags的设置

  flags可以是任何下面标记的组合(以位或运算 | 组合):PREG_SPLIT_NO_EMPTY——如果这个标记被设置,preg_split()将进返回分隔后的非空部分;PREG_SPLIT_DELIM_CAPTURE——如果这个标记设置了,用于分隔的模式中的括号表达式将被捕获并返回;PREG_SPLIT_OFFSET_CAPTURE——如果这个标记被设置,对于每一个出现的匹配返回时将会附加字符串偏移量。注意:这将会改变返回数组中的每一个元素,使其每个元素成为一个由第0个元素为分隔后的子串,第1个元素为该子串在subject中的偏移量组成的数组

<?php//使用逗号或空格(包含" ", , , 
, f)分隔短语$keywords = preg_split("/[s,]+/", "hypertext language, programming");/*Array
(
    [0] => hypertext
    [1] => language
    [2] => programming
) */print_r($keywords);?>
Copy after login

转义

【preg_quote()】

  preg_quote()转义正则表达式字符

string preg_quote ( string $str [, string $delimiter = NULL ] )
Copy after login

  正则表达式特殊字符有: . + * ? [ ^ ] $ ( ) { } = ! < > | : -

<?php$keywords = &#39;$40 for a g3/400&#39;;$keywords = preg_quote($keywords, &#39;/&#39;);echo $keywords; // 返回 $40 for a g3/400?>
Copy after login

以上就是前端学PHP之正则表达式函数的全部内容。

相关推荐:php中文网

The above is the detailed content of PHP regular expression function. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

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

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

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

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

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

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

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

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

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

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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 PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

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.

See all articles