PHP:获取具有特定索引的两个字符之间的字符串

I am a beginner of PHP. I have string:

$fullstring = "this is [tag]dog[/tag], [tag]cat[/tag], [tag]lion[/tag]";

I want to get string "cat" from my $fullstring.

I used to try with this:

Get substring between two strings PHP

But I can only get the first string (dog). Thank you for your time.

Thet Cartter.

Try to use preg_match_all

$fullstring = "this is [tag]dog[/tag], [tag]cat[/tag], [tag]lion[/tag]";

preg_match_all("'\[tag\](.*?)\[\/tag\]'si", $fullstring, $match);

foreach($match[1] as $val){
    echo $val, ' ';
}
// result: dog cat lion

To get only the content of the second tag (which is cat now)

echo $mathc[1][1]
// result: cat

You're looking for preg_match() function. An example below may help you out.

 $fullString = "this is [tag]dog[/tag], [tag]cat[/tag], [tag]lion[/tag]";
 $regex = "/\[tag\]\w+\[\\tag\]/";
 preg_match($regex, $fullString, $matches);
 foreach($matches as $match){
     echo $match;
 }
 // result, dog, cat, lion

This is a modified version of this answer. This function will return all instances it can find based on what you want to search.

    function getContents($str, $startDelimiter, $endDelimiter, $needle) {
    $contents = array();
    $startDelimiterLength = strlen($startDelimiter);
    $endDelimiterLength = strlen($endDelimiter);
    $startFrom = $contentStart = $contentEnd = 0;
    while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) {
        $contentStart += $startDelimiterLength;
        $contentEnd = strpos($str, $endDelimiter, $contentStart);
        if (false === $contentEnd) {
            break;
        }
        $tempString = substr($str, $contentStart, $contentEnd - $contentStart);
        if ($tempString == $needle) {
            $contents[] = $tempString;
        }
        $startFrom = $contentEnd + $endDelimiterLength;
    }

    return $contents;
}

I try to modify the old function [http://www.justin-cook.com/wp/2006/03/31/php-parse-a-string-between-two-strings/]. I got this:

function get_string_between($string, $start, $end, $index){ if ($index <= 0) return ''; $string = ' ' . $string; $ini = 0; $x = 1; while ($x <= $index) { $ini = strpos($string, $start, $ini + 1); if ($ini == 0) return ''; $x++; } $ini += strlen($start); $len = strpos($string, $end, $ini) - $ini; return substr($string, $ini, $len); }

$fullstring = "this is [tag]dog[/tag], [tag]cat[/tag], [tag]lion[/tag]; echo get_string_between($fullstring, "[tag]", "[/tag]", 2); // Result = cat