Extract Substrings Between Brackets in PHP

In PHP, extracting substrings between brackets can be done using various approaches. We have to print the word that is present in between the brackets.

These are the following approaches:

Table of Content

  • Using Regular Expressions
  • Using strpos() and substr() functions

Using Regular Expressions

In this approach, we are using the preg_match_all function with the pattern /\[(.*?)\]/ to match substrings between brackets. Here the pattern /\[(.*?)\]/ uses \[ and \] to match literal opening and closing brackets and (.*?) to match any character between them.

Syntax:

preg_match_all(pattern, string, matches);

Example: This example uses Regular Expressions Extract substrings between brackets in PHP.

PHP
<?php
$string = "Hello [Yuvraj], Welcome to [w3wiki]!";
preg_match_all("/\[(.*?)\]/", $string, $matches);
$extracted = $matches[1];

foreach ($extracted as $substring) {
    echo $substring . "\n";
}
?>

Output
Yuvraj
w3wiki

Using strpos() and substr() functions

In this approach we are using strpos to find the position of the opening bracket “[“ and strpos again to find the position of the closing bracket “]”. Then we use substr to extract the substring between the two positions.

Syntax:

strpos(string, bracket);
substr(string, start, end);

Example: This example uses strpos and substr functions Extract substrings between brackets in PHP.

PHP
<?php
$string = "This is [sample] text [with] brackets";
$start = 0;

while (($start = strpos($string, '[', $start)) !== false) {
    $end = strpos($string, ']', $start);
    if ($end === false) {
        break;
    }

    $extracted = substr($string, $start + 1
                        , $end - $start - 1);
    echo $extracted . PHP_EOL;

    $start = $end + 1;
}

?>

Output
sample
with