How to use strpos() and substr() functions In PHP

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

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

Similar Reads

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

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