How can I get string between two characters [string] ? PHP

后端 未结 2 1497
鱼传尺愫
鱼传尺愫 2021-01-01 03:34
$string1 = \"This is test [example]\";
$string2 = \"This is test [example][2]\";
$string3 = \"This [is] test [example][3]\";

How can I get the foll

2条回答
  •  渐次进展
    2021-01-01 04:37

    For those wary of regex, here's a solution sans that crazy regex syntax. :-) It used to really irritate me that something like this wasn't native to PHP's string functions so I built one...

    // 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 "

    html_tools.php BetweenString() FAILED. \$InputString is not a string.

    \n"; } return; } if (($StartLoc = strpos($InputString, $StartStr, $StartLoc)) === false) { if ($Echo) { echo "

    html_tools.php BetweenString() FAILED. Could not find \$StartStr '{$StartStr}' within \$InputString |{$InputString}| starting from \$StartLoc ({$StartLoc}).

    \n"; } return; } $StartLoc += strlen($StartStr); if (!$EndStr) { $EndStr = $StartStr; } if (!$EndLoc = strpos($InputString, $EndStr, $StartLoc)) { if ($Echo) { echo "

    html_tools.php BetweenString() FAILED. Could not find \$EndStr '{$EndStr}' within \$InputString |{$InputString}| starting from \$StartLoc ({$StartLoc}).

    \n"; } return; } $BetweenString = substr($InputString, $StartLoc, ($EndLoc-$StartLoc)); if ($Echo) { echo "

    html_tools.php BetweenString() Returning |'{$BetweenString}'| as found between \$StartLoc ({$StartLoc}) and \$EndLoc ({$EndLoc}).

    \n"; } return $BetweenString; }

    Of course this can be condensed quite a bit. To save someone else the effort of cleaning it up:

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

提交回复
热议问题