Home > Backend Development > PHP Tutorial > PHP怎么实现正则匹配所有括号中的内容

PHP怎么实现正则匹配所有括号中的内容

PHPz
Release: 2020-09-04 14:01:50
Original
4161 people have browsed it

PHP实现正则匹配所有括号中的内容的方法:首先创建一个PHP文件;然后输入PHP正则匹配代码,如:“preg_match_all($strPattern, $strSubject, $arrMatches);”;最后运行该文件即可。

PHP怎么实现正则匹配所有括号中的内容

PHP怎么实现正则匹配所有括号中的内容?

正则表达式:(?<=【)[^】]+

注:以匹配中文括号中内容为例,如果匹配非中文括号,则需要在括号前增加转义符

PHP实现示例:

<?php
    $strSubject = "abc【111】abc【222】abc【333】abc";
    $strPattern = "/(?<=【)[^】]+/";
    $arrMatches = [];
    preg_match_all($strPattern, $strSubject, $arrMatches);
    var_dump($arrMatches);
Copy after login

执行结果:

~ » php mytest/test_preg.php                                                                                 iwaimai@bogon
array(1) {
 [0]=>
 array(3) {
  [0]=>
  string(3) "111"
  [1]=>
  string(3) "222"
  [2]=>
  string(3) "333"
 }
}
Copy after login

解析:

1、(?<=【)

第一个表达式是一个『非获取匹配』,即匹配括号,但并不获取括号;

5f8faac57d7eb962a66564a5e95297d.png

2、[^】]+

第二个表达式中[]匹配单个字符,^】代表除了】的字符,+是限定符代表匹配前面子表达式一次或多次,即匹配除了】的连续多个字符;

组合起来即实现了预期效果~

更多相关知识,请访问PHP中文网

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template