Home  >  Article  >  Backend Development  >  PHP regular expression group capture implementation method

PHP regular expression group capture implementation method

小云云
小云云Original
2018-02-05 09:15:341903browse

本文主要和大家介绍PHP实现正则表达式分组捕获操作,结合实例形式分析了php正则表达式获取分组捕获操作的相关实现方法与使用注意事项,需要的朋友可以参考下,希望能帮助到大家。

经过测试,发现php正则表达式获取分组捕获是从$0开始,而平时工作中JavaScript中的正则是$1..$9

在提取项目代码中的汉字时,因为当时操作速度很快(赶时间),很担心当时.properties的文件{\d}的数字顺序搞错了:

1、可能从{1}开始,而不是从{0}开始

2、可能跳着写了,比如第一个是{0}第二个需要替换的地方却写着{2}

因为使用人工手动操作的,所以这种情况是难以避免,只能说减少误操作。写完了,得再检查一遍,这个遇到困难了,二三千行的代码,用眼睛一行一行查,那的比较累了,而且还不一定能检查出来。一多就容易出错,而且行与行之间靠的太近了,字又太小…

突然想起来,觉得php可以节省一点时间,读取文件,然后将关键的地方标红…

然后就开始了:php读取文件,然后逐行的读取,使用正则表达式匹配符合{\d}的行,然后将{\d}的地方使用红色进行重点的标记,之后人工去查看每一行是能是符合规则。代码不对,却很受用,至少省了用眼睛去一个一个检查的时间:

这样一眼扫过去,就能很清楚的看出每一行顺序是否都写对了,写错了的行,前面有行号,找到相应行再改改.


<!Doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>检测中文替换文字的正确性</title>
</head>
<?php
 $filename = "C:\test.properties";
 $mode = "r";
 $file_handle = fopen($filename, $mode);
 $lineNum = 0;
 $pattern = "/{\d}[^{}]+/";
 if ($file_handle) {
  while (!feof($file_handle)) {
   ++$lineNum;
   $line = fgets($file_handle);
   if (preg_match($pattern, $line)) {
    $line = preg_replace("/{\d}/", "<font color=&#39;red&#39;>$0</font>", $line);
    echo "行".$lineNum.":".$line."<br/><br/><br/>";
   }
  }
 } else {
  echo "文件读取失败";
 }
 fclose($file_handle);
?>
</html>

相关推荐:

PHP之正则表达式捕获组与非捕获组的详解

捕获未处理的Promise错误

Node.js 中的未捕获异常怎么解决

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

Statement:
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