好的,所以我有一个像这样的字符串
$sText = '[post:1]Some test here......[/post]';
现在我想提取其中的“有些测试......”中的文本,我还希望括号内的数字“1”[post:1]。我试过寻找一个解决方案,但还找不到好的解决方案。
我尝试使用此
获取括号内的文本preg_match_all('/\[(.*?)\]/', $sText, $out);
它给了我这个
Array
(
[0] => Array
(
[0] => [post:1]
[1] => [/post]
)
[1] => Array
(
[0] => post:1
[1] => /post
)
)
我可以通过使用爆炸或任何其他方式获取数字然后我可以通过使用正则表达式删除括号但这听起来像太多的正则表达式来获取文本。对此有没有更好的解决方案/想法?好吧,我对正则表达式并不擅长。
答案 0 :(得分:1)
试试这个:
preg_match_all('~\[(?<tag>\w+):(?<nbr>\d+)](?<content>(?>[^[]++|\[(?!/\1]))+)\[/\1]~',
$sText, $matches, PREG_SET_ORDER);
foreach($matches as $match) {
echo '<br/>' . $match['tag'] . "\t" . $match['nbr'] . "\t" . $match['content'];
}
模式细节:
~ # pattern delimiter
\[ # literal [ (must be escaped)
(?<tag>\w+) # named capture with the tag name (alphanumeric + _)
: # literal :
(?<nbr>\d+) # named capture for the number
] # literal ]
(?<content> # named capture for the content inside tags
(?> # open an atomic group
[^[]++ # all characters that are not a [ one or more times
| # OR
\[(?!/\1]) # literal [ not follow by "/tagname]"
)+ # close the atomic group, repeat it 1 one more times
) # close the named capture: content
\[/ # literal [/
\1 # reference to the capturing group 1 (tagname)
] # literal ]
~ # pattern delimiter
答案 1 :(得分:1)
我正在考虑这样的事情
$sText = '[post:1]Some test here......[/post]';
$pattern = '/\:(\d+)\](.*?)\[/';
preg_match_all($pattern, $sText, $a);
var_dump($a);
返回
array (size=3)
0 =>
array (size=1)
0 => string ':1]Some test here......[' (length=24)
1 =>
array (size=1)
0 => string '1' (length=1)
2 =>
array (size=1)
0 => string 'Some test here......' (length=20)