Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php preg_match between bracket

i want to use preg_match to find text between bracket for example: $varx = "(xx)";

final output will be $match = 'xx';

another example $varx = "bla bla (yy) bla bla";

final output will be something like this $match = 'yy';

in other words it strips out bracket. i'm still confusing with regular expression but found that sometimes preg match is more simple solution. searching other example but not meet my need.

like image 448
apis17 Avatar asked Oct 11 '11 17:10

apis17


2 Answers

Try something like this:

preg_match('/(?<=\()(.+)(?=\))/is', $subject, $match);

Now it will capture newlines.

like image 82
Biotox Avatar answered Sep 23 '22 07:09

Biotox


Bear in mind that brackets are special characters in RegExps so you'll need to escape them with a backslash - you've also not made it clear as to what possible range of characters can appear between ( ... ) or whether there can be multiple instances of ( ... ).

So, your best bet might be a RegExp like: /\(([^\)]*)\)/ which will match many occurrences of ( ... ) containing any (or no) characters between the parentheses.

Try preg_match('/\(([^\)]*)\)/', $sString, $aMatches)

EDIT: (example)

<?php
$sString = "This (and) that";
preg_match_all('/\(([^\)]*)\)/', $sString, $aMatches);
echo $aMatches[1][0];
echo "\n\n\n";
print_r($aMatches);
?>

Which results in:

and


Array
(
    [0] => Array
        (
            [0] => (and)
        )

    [1] => Array
        (
            [0] => and
        )

)

So the string "and" is stored in $aMatches[1][0] :)

like image 22
CD001 Avatar answered Sep 23 '22 07:09

CD001