使用正则表达式查找方括号之间的值


Using regex to find value between square brackets

我想找到方括号内的值。比如说我有一个这样的字符串

$str = "This is a test string. I want to get value between [this] and [/this]";

因此,为了更清楚地解释它,我想找到[this][/this],然后找到它们之间的and。我在这里找到了一些关于寻找方括号内的值的线索,但这不是我的情况,它没有帮助。Regex对我来说就是希伯来语如果你明白我的意思

你可以使用这个正则表达式:

'[[^]]*'][^[]*'[[^]]*']

在线Regex演示

您可以使用下面的正则表达式,

'[.*?'][^']]*']

演示

你的代码应该是,

<?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]