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);
<?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