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

4
$string1 = "This is test [example]";
$string2 = "This is test [example][2]";
$string3 = "This [is] test [example][3]";

我该如何获得以下结果?
For $string1 -> example
For $string2 -> example*2
For $string3 -> is*example*3

在任何编程语言中,循环遍历字符,如果遇到 [ 就设置标识并获取直到 ] 的所有内容,然后取消标识 :) - Jashwant
2个回答

7
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
        )

)

以下是rregex的说明:

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

你能解释一下正则表达式吗?据我所知,/是开始正则表达式的符号。\用于转义[[用于包含一组字符,对吗?你能解释一下完整的正则表达式吗? - Jashwant

5

对于那些不熟悉正则表达式的人,这里提供一种不需要使用复杂正则语法的解决方案。 :-) 以前我非常不理解为什么 PHP 的字符串函数中没有原生支持这样的功能,所以我自己构建了一个...

// 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));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接