How to match a substring within 2 square brackets using RegEx in PHP

1 Answer

0 votes
function extractBracketedContent($text) {
    preg_match_all('/\[(.*?)\]/', $text, $matches);

    return $matches[1]; // Only the content inside the brackets
}

$input = "This is a [sample] string with [multiple] square brackets.";

$extracted = extractBracketedContent($input);

foreach ($extracted as $item) {
    echo $item . PHP_EOL;
}



/*
run:

sample
multiple

*/

 



answered Jul 19, 2025 by avibootz
...