如何获取两个字符之间的字符串[字符串]?PHP

如何获取两个字符之间的字符串[字符串]?PHP,php,string,Php,String,如何得到以下结果 $string1 = "This is test [example]"; $string2 = "This is test [example][2]"; $string3 = "This [is] test [example][3]"; 以下是对rregex的解释: preg_match_all('/\[([^\]]+)\]/', $str, $matches); php > preg_match_all('/\[([^\]]+)\]/', 'This [is] te

如何得到以下结果

$string1 = "This is test [example]";
$string2 = "This is test [example][2]";
$string3 = "This [is] test [example][3]";
以下是对rregex的解释:

preg_match_all('/\[([^\]]+)\]/', $str, $matches);

php > preg_match_all('/\[([^\]]+)\]/', 'This [is] test [example][3]', $matches);
php > print_r($matches);
Array
(
    [0] => Array
        (
            [0] => [is]
            [1] => [example]
            [2] => [3]
        )

    [1] => Array
        (
            [0] => is
            [1] => example
            [2] => 3
        )

)

对于那些担心正则表达式的人,这里有一个解决方案,它没有那种疯狂的正则表达式语法。:-)它曾经让我非常恼火,像这样的东西不是PHP的字符串函数所固有的,所以我构建了一个

\[ # literal [
( # group start
    [^\]]+ # one or more non-] characters
) # group end
\] # literal ]

在任何语言中,如果遇到
[
set flag并抓取所有字符,直到
]
和unset flag:)您能解释一下正则表达式吗?就我所知
/
启动正则表达式
`转义
[[`包含一组字符?对吗?你能解释完整的正则表达式吗?
\[ # literal [
( # group start
    [^\]]+ # one or more non-] characters
) # group end
\] # literal ]
// Grabs the text between two identifying substrings in a string. If $Echo, it will output verbose feedback.
function BetweenString($InputString, $StartStr, $EndStr=0, $StartLoc=0, $Echo=0) {
    if (!is_string($InputString)) { if ($Echo) { echo "<p>html_tools.php BetweenString() FAILED. \$InputString is not a string.</p>\n"; } return; }
    if (($StartLoc = strpos($InputString, $StartStr, $StartLoc)) === false) { if ($Echo) { echo "<p>html_tools.php BetweenString() FAILED. Could not find \$StartStr '{$StartStr}' within \$InputString |{$InputString}| starting from \$StartLoc ({$StartLoc}).</p>\n"; } return; }
    $StartLoc += strlen($StartStr);
    if (!$EndStr) { $EndStr = $StartStr; }
    if (!$EndLoc = strpos($InputString, $EndStr, $StartLoc)) { if ($Echo) { echo "<p>html_tools.php BetweenString() FAILED. Could not find \$EndStr '{$EndStr}' within \$InputString |{$InputString}| starting from \$StartLoc ({$StartLoc}).</p>\n"; } return; }
    $BetweenString = substr($InputString, $StartLoc, ($EndLoc-$StartLoc));
    if ($Echo) { echo "<p>html_tools.php BetweenString() Returning |'{$BetweenString}'| as found between \$StartLoc ({$StartLoc}) and \$EndLoc ({$EndLoc}).</p>\n"; }
    return $BetweenString; 
}
// Grabs the text between two identifying substrings in a string.
function BetweenStr($InputString, $StartStr, $EndStr=0, $StartLoc=0) {
    if (($StartLoc = strpos($InputString, $StartStr, $StartLoc)) === false) { return; }
    $StartLoc += strlen($StartStr);
    if (!$EndStr) { $EndStr = $StartStr; }
    if (!$EndLoc = strpos($InputString, $EndStr, $StartLoc)) { return; }
    return substr($InputString, $StartLoc, ($EndLoc-$StartLoc));
}