我已经坐了几个小时来找出 php 中 preg_match_all 函数的 regExp。
我的问题是我想要字符串中的两个不同的东西。
假设您有字符串“代码很有趣[并且对大脑有益。]但是[大脑]很累。”
我需要的是一个数组,其中包含括号外的所有单词和括号内的文本作为一个字符串。
像这样的东西
[0] => Code
[1] => is
[2] => fun
[3] => and good for the brain.
[4] => But
[5] => the
[6] => brain is
[7] => tired.
非常感谢帮助。
您也可以尝试下面的正则表达式,
(?<=\[)[^\]]*|[.\w]+
DEMO http://regex101.com/r/gJ0hU7/3
Code:
<?php
$data = "Code is fun [and good for the brain.] But the [brain is] tired.";
$regex = '~(?<=\[)[^\]]*|[.\w]+~';
preg_match_all($regex, $data, $matches);
print_r($matches);
?>
Output:
Array
(
[0] => Array
(
[0] => Code
[1] => is
[2] => fun
[3] => and good for the brain.
[4] => But
[5] => the
[6] => brain is
[7] => tired.
)
)
第一个外观绑定(?<=\[)[^\]]*
匹配大括号内出现的所有字符[]
和第二个[.\w]+
匹配剩余字符串中的一个或多个单词字符或点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)