3

I have a string with State name and code like this

KT16(Ottershaw)

Now i need to extract text from (). I need to extract Ottershaw. How can i do this with php.

2

4 Answers 4

7

should be :

preg_match('/\(([^\)]*)\)/', 'KT16(Ottershaw)', $matches);
echo $matches[1];
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for quick answer. Regex is great i like the way
6

Just get the substring between the first opening bracket and the last closing bracket:

$string = "KT16(Ottershaw)";
$strResult = substr($string, stripos($string, "(") +1,strrpos($string, ")") - stripos($string, "(")-1);  

4 Comments

Yeah, not all the problems need a regex
No. It is also working with $string = "KT16(Otte (rshaw))";
What about $string = "KT16(Otte) test (rshaw)"; ? I'll still give you +1 thought :p
Now i understand what you mean... Yes you are right, but it wasn't in the question. I thought it would be nice to get it even there are further brackets in the string.
1

This is a sample code to extract all the text between '[' and ']' and store it 2 separate arrays(ie text inside parentheses in one array and text outside 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"
}

Comments

0

The following RegEx should work:

/\[(.*?)\]/ 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.