PHP - preg_match() 函数



语法

int preg_match (string pattern, string string [, array pattern_array], [, int $flags [, int $offset]]]);

定义和用法

preg_match() 函数搜索字符串中的模式,如果模式存在则返回 true,否则返回 false。

如果提供了可选的输入参数 pattern_array,则 pattern_array 将包含搜索模式中包含的子模式的各个部分(如果适用)。

如果此标志作为 PREG_OFFSET_CAPTURE 传递,则对于每次出现的匹配,还将返回附加的字符串偏移量。

通常,搜索从主题字符串的开头开始。可选参数 offset 可用于指定开始搜索的备用位置。

返回值

  • 如果模式存在则返回 true,否则返回 false。

示例

以下是代码片段,将此代码复制并粘贴到文件中并验证结果。

<?php
   $line = "Vi is the greatest word processor ever created!";
   // perform a case-Insensitive search for the word "Vi"
   
   if (preg_match("/\bVi\b/i", $line, $match)) :
      print "Match found!";
      endif;
?>

这将产生以下结果:

Match found!
php_regular_expression.htm
广告
© . All rights reserved.