PHP-PCRE正则表达式函数

时间:2023-03-09 15:44:46
PHP-PCRE正则表达式函数

PCRE正则表达式函数

PCRE字符类

\\b        词边界

\\d        匹配任意数字

\\s        匹配任意空白,如TAB制表符或空格

\\t        匹配一个TAB制表符

\\w        匹配包含字母与数字的字符

PCRE匹配

在绝大多数PCRE示例中,分隔符都使用一个/,可在引号内表达式的开始和结尾出看到,在PCRE表达式中的最后一个分隔符/后面,可添加一个修饰符来更改正则表达式的行为 1.preg_match() 在字符串中查找匹配项,它需要两个参数:正则表达式(parttern)与字符串(string)

  1. <?php
  2. $email="raymond.du@yhys.com";
  3. echo preg_match("/^([a-zA-Z0-9])+([.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+([.a-zA-Z0-9_-]+)+[a-zA-Z0-9_-]$/",$email);
  4. ?>

2.preg_quote() 在每个正则表达式语法的前面加入一个转义字符,也就是反斜线(\)

  1. <?php
  2. $string="$3000 你会去周游世界吗,^-^";
  3. echo preg_quote($string);
  4. ?>

3.preg_split() 表示用正则表达式分隔字符串

  1. <?php
  2. $string="+杜江+++林林++++++++++++北京大学+++*";
  3. $fields=preg_split("/\+{1,}/",$string);
  4. foreach ($fields as $field) {
  5. echo $field."<br>";
  6. }
  7. ?>

4.preg_grep()

  1. <?php
  2. $goods=array("家居","家具","窗体","家装");
  3. //把"家"字打头的数组内容取出生成一个新数组$item
  4. $item=preg_grep("/^家/",$goods);
  5. print_r($item);
  6. ?>

5.preg_replcae() 格式:mixed preg_replcae(mixed pattern,mixed replace,ent,mixed subject); 这个函数会將string中符合表达式pattern的字符串全部替换为表达式replacement.如果 replacement中需要包含pattern的部分字符,则可以使用"()"来记录,在replacement中只需要用"\\1"来读取 比如:將用户输入的一段文字进行分析,如果有http:的字样,则认为是一个网址,并加上超链接

  1. <?php
  2. $string="欢迎炎黄养生网 http://www.yhys.com/";
  3. echo preg_replace("/http:\/\/(.*)\//","<a href=\"\${0}\">\${0}</a>",$string);
  4. ?>

6.preg_replace_callback() 该函数使用回调函数执行正则表达式的搜索和替换

  1. <?php
  2. //回调函数,即用户自定义替换函数
  3. function do_spam($matches){
  4. $pre_array=array('gg'=>'帅哥','mm'=>'美眉','pp'=>'漂亮');
  5. if (isset($pre_array[$matches[1]])){
  6. return $matches[1] . "(" . $pre_array[$matches[1]] . ")";
  7. }else {
  8. return $matches[1];
  9. }
  10. }
  11. //原字符串
  12. $string="这位<spam>gg</spam>的<spam>mm</spam>很<spam>pp</spam>哦";
  13. //从<spam></spam>中搜索匹配的子进行替换
  14. $new_string=preg_replace_callback("/<spam>(.*)<\/spam>/U",'do_spam',$string);
  15. print_r($new_string);
  16. ?>