0

How to extract string between [ and ]

I tried using trim() but I believe trim() only works in removing spaces.

ex. [abc123-ab:ab123] output should be -> abc123-ab:ab123

2 Answers 2

2

Trim will work if you give it that second argument:

trim($str, '[]');

but if the the "[]"s will always be on the beginning and end of the string (they need to be for trim to work), a better solution might be substr:

substr($str, 1, -1);
Sign up to request clarification or add additional context in comments.

2 Comments

trim($str, '[]'); won't work I tried it already. And for substr($str, 1, -1), not all has [] so this won't be the right one to use for this situation but it's working though for those with [].
The trim seems right to me, am I missing something: foreach (array('[123]', '456') as $x) { var_dump(trim($x, '[]')); } Remember trim returns the new string, it doesn't modify it in place.
0
function between($t1,$t2,$page) {
    $p1=stripos($page,$t1);
    if($p1!==false) {
        $p2=stripos($page,$t2,$p1+strlen($t1));
                if($p2===false) { return false; }
    } else {
        return false;
    }
    return substr($page,$p1+strlen($t1),$p2-$p1-strlen($t1));
}

$mytext=between('[',']',$str);
if($mytext!==false) {
   //do something here
}

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.