Extract text from string containing brackets in PHP
4 answers
This is a sample code to extract all the text between '[' and ']' and store it in 2 separate arrays (i.e. the text inside the parentheses in one array and the text outside the parentheses in another array)
function extract_text($string)
{
$text_outside=array();
$text_inside=array();
$t="";
for($i=0;$i<strlen($string);$i++)
{
if($string[$i]=='[')
{
$text_outside[]=$t;
$t="";
$t1="";
$i++;
while($string[$i]!=']')
{
$t1.=$string[$i];
$i++;
}
$text_inside[] = $t1;
}
else {
if($string[$i]!=']')
$t.=$string[$i];
else {
continue;
}
}
}
if($t!="")
$text_outside[]=$t;
var_dump($text_outside);
echo "\n\n";
var_dump($text_inside);
}
Output: extract_text ("hello, how are you?"); will produce:
array(1) {
[0]=>
string(18) "hello how are you?"
}
array(0) {
}
extract_text ("hello [http://www.google.com/test.mp3] how are you?"); will produce
array(2) {
[0]=>
string(6) "hello "
[1]=>
string(13) " how are you?"
}
array(1) {
[0]=>
string(30) "http://www.google.com/test.mp3"
}
0
source to share