美文网首页
php常见的正则匹配操作方法

php常见的正则匹配操作方法

作者: 知码客 | 来源:发表于2024-04-20 21:30 被阅读0次

在PHP中,你可以使用preg_match函数进行正则表达式匹配。以下是一些常见的PHP正则表达式匹配示例:

  1. 匹配字符串中的数字:
$pattern = '/\d+/';
$string = 'Hello, 12345 is a number.';
if (preg_match($pattern, $string, $matches)) {
    echo "Found number: " . $matches[0];
}
  1. 匹配电子邮件地址:
$pattern = '/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/';
$string = 'Contact us at info@example.com.';
if (preg_match($pattern, $string, $matches)) {
    echo "Found email: " . $matches[0];
}
  1. 匹配URL:
$pattern = '/(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/';
$string = 'Visit <http://www.example.com> for more information.';
if (preg_match($pattern, $string, $matches)) {
    echo "Found URL: " . $matches[0];
}
  1. 匹配HTML标签:
$pattern = '/<[^>]+>/';
$string = '<p>This is a paragraph.</p>';
if (preg_match_all($pattern, $string, $matches)) {
    echo "Found HTML tags: ";
    print_r($matches[0]);
}
  1. 匹配边界字符(例如单词边界):
$pattern = '/\bword\b/';
$string = 'This is a word in a sentence.';
if (preg_match($pattern, $string, $matches)) {
    echo "Found word boundary: " . $matches[0];
}

这些只是一些常见的PHP正则表达式匹配示例,你可以根据自己的需求进行更复杂的匹配操作。

还有很多很多需要我们持之以恒的去学习和研究一下,路虽远行则将至

相关文章

  • PHP常用正则表达式汇总

    PHP常用正则表达式汇总 正则表达式在 PHP 中的应用在 PHP 应用中,正则表达式主要用于: 正则匹配:根据正...

  • 匹配中文

    javascript匹配正则中文:var reg=/[\u4e00-\u9fa5]+/gi; PHP中正则匹配中文...

  • 常用正则表达式

    常用正则表达式大全!(例如:匹配中文、匹配html)目录导航一、常见正则表达式二、正则表达式应用一、常见正则表达式...

  • php常用的正则匹配

    php常用的正则匹配 匹配手机号码 匹配邮箱 电话号码匹配 } 匹配url 匹配身份证号 匹配邮编 匹配ip 匹配...

  • php学习笔记(四)

    正则表达式 PHP中使用PCRE库函数进行正则匹配,比如上例中的preg_match用于执行一个正则匹配,常用来判...

  • 巧用正则表达式

    基本 常见正则文本 |代码|说明||:---|:---:|---:||.|匹配除换行以外的任意字符||\w|匹配字...

  • 《JavaScript正则表达式迷你书》读书笔记

    正则基础 常见简写形式 量词 修饰符 匹配位置 匹配开头与结尾 /^|$/g: 匹配列 /^|$/gm: 匹配行,...

  • PHP如何判断空

    PHP类型比较 PHP自动类型转换(弱语言) PHP去除空格 1、去除两边的空格trim($arr) 2、正则匹配...

  • PHP正确匹配中文方式

    PHP正则表达式正确匹配中文方式 $str ="php编程"; if(preg_match("/^[\x{4e00...

  • PHP正则 "?" 使用

    php 中贪婪匹配 与 惰性匹配 贪婪匹配:尽可能多的匹配多的字符比如 正则表达式 "m.*n" 它将匹配最长以m...

网友评论

      本文标题:php常见的正则匹配操作方法

      本文链接:https://www.haomeiwen.com/subject/umopxjtx.html