PHP preg_match() 函数

PHP 教程 · 2019-01-31 12:41:30

preg_last_error 函数用于执行一个正则表达式匹配。

语法

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

搜索 subject 与 pattern 给定的正则表达式的一个匹配。

参数说明:

  • $pattern: 要搜索的模式,字符串形式。

  • $subject: 输入字符串。

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

  • $flags:flags 可以被设置为以下标记值:

    1. PREG_OFFSET_CAPTURE: 如果传递了这个标记,对于每一个出现的匹配返回时会附加字符串偏移量(相对于目标字符串的)。 注意:这会改变填充到matches参数的数组,使其每个元素成为一个由 第0个元素是匹配到的字符串,第1个元素是该匹配字符串 在目标字符串subject中的偏移量。

  • offset: 通常,搜索从目标字符串的开始位置开始。可选参数 offset 用于 指定从目标字符串的某个未知开始搜索(单位是字节)。

返回值

返回 pattern 的匹配次数。 它的值将是 0 次(不匹配)或 1 次,因为 preg_match() 在第一次匹配后 将会停止搜索。preg_match_all() 不同于此,它会一直搜索subject 直到到达结尾。 如果发生错误preg_match()返回 FALSE。

实例

查找文本字符串"php":

<?php //模式分隔符后的"i"标记这是一个大小写不敏感的搜索 if (preg_match("/php/i", "PHP is the web scripting language of choice.")) { echo "查找到匹配的字符串 php。"; } else { echo "未发现匹配的字符串 php。"; } ?>

执行结果如下所示:

查找到匹配的字符串 php。

查找单词"word"

<?php /* 模式中的\b标记一个单词边界,所以只有独立的单词"web"会被匹配,而不会匹配 * 单词的部分内容比如"webbing" 或 "cobweb" */ if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) { echo "查找到匹配的字符串。\n"; } else { echo "未发现匹配的字符串。\n"; } if (preg_match("/\bweb\b/i", "PHP is the website scripting language of choice.")) { echo "查找到匹配的字符串。\n"; } else { echo "未发现匹配的字符串。\n"; } ?>

执行结果如下所示:

查找到匹配的字符串。
未发现匹配的字符串。

获取 URL 中的域名

<?php // 从URL中获取主机名称 preg_match('@^(?:http://)?([^/]+)@i', "http://www.codercto.com/index.html", $matches); $host = $matches[1]; // 获取主机名称的后面两部分 preg_match('/[^.]+\.[^.]+$/', $host, $matches); echo "domain name is: {$matches[0]}\n"; ?>

执行结果如下所示:

domain name is: codercto.com

使用命名子组

<?php $str = 'foobar: 2008'; preg_match('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches); /* 下面例子在php 5.2.2(pcre 7.0)或更新版本下工作, 然而, 为了后向兼容, 上面的方式是推荐写法. */ // preg_match('/(?<name>\w+): (?<digit>\d+)/', $str, $matches); print_r($matches); ?>

执行结果如下所示:

Array
(
    [0] => foobar: 2008
    [name] => foobar
    [1] => foobar
    [digit] => 2008
    [2] => 2008
)

点击查看所有 PHP 教程 文章: https://www.codercto.com/courses/l/5.html

查看所有标签

Chinese Authoritarianism in the Information Age

Chinese Authoritarianism in the Information Age

Routledge / 2018-2-13 / GBP 115.00

This book examines information and public opinion control by the authoritarian state in response to popular access to information and upgraded political communication channels among the citizens in co......一起来看看 《Chinese Authoritarianism in the Information Age》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具