问题
I want to find the value inside square brackets. Let's say I have a string like this
$str = "This is a test string. I want to get value between [this] and [/this]";
So, to explain it pretty clearly, I want to find [this]
and [/this]
and then the 'and
' between them. I found some threads here about finding the value inside square brackets but that's not exactly my case, and it did not help. Regex to me is Hebrew to me if you know what I mean.
回答1:
You could use the below regex,
\[.*?\][^\]]*\]
DEMO
Your code would be,
<?php
$str = "This is a test string. I want to get value between [this] and [/this]";
$regex = '~\[.*?\][^\]]*\]~';
if (preg_match($regex, $str, $m)) {
$yourmatch = $m[0];
echo $yourmatch;
}
?> //=> [this] and [/this]
回答2:
You can use this regex:
\[[^]]*\][^[]*\[[^]]*\]
Online Regex Demo
来源:https://stackoverflow.com/questions/24553265/using-regex-to-find-value-between-square-brackets