Extract text from string containing brackets in PHP
I have a string with a name and a code like
KT16(Ottershaw)
Now I need to extract text from ()
. I need to extract Ottershaw. How can I do this using php.
+3
Muhammad raheel
source
to share
4 answers
it should be:
preg_match('/\(([^\)]*)\)/', 'KT16(Ottershaw)', $matches);
echo $matches[1];
+7
Devang rathod
source
to share
Just get the substring between the first open brace and the last closing brace:
$string = "KT16(Ottershaw)";
$strResult = substr($string, stripos($string, "(") +1,strrpos($string, ")") - stripos($string, "(")-1);
+5
devOp
source
to share
The following RegEx should work:
/\[(.*?)\]/
0
BenM
source
to share
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
Sachin Murali G
source
to share