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

时间:2014-07-03 12:05:53

标签: php regex preg-match

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

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

所以,为了清楚地解释它,我想找到[this][/this],然后找到' and'它们之间。我在这里发现了一些关于在方括号内找到值的线程,但这不完全是我的情况,并没有帮助。如果你知道我的意思,对我来说是正则表达式希伯来语。

2 个答案:

答案 0 :(得分:1)

您可以使用此正则表达式:

\[[^]]*\][^[]*\[[^]]*\]

Online Regex Demo

答案 1 :(得分:0)

您可以使用以下正则表达式

\[.*?\][^\]]*\]

DEMO

您的代码将是,

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