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.
Try something like this:
preg_match('/(?<=\()(.+)(?=\))/is', $subject, $match);
Now it will capture newlines.
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] :)
preg_match('/\((.*?)\)/i', $varx, $match);
Adding the s
modifier allows line-breaks between parentheses. For example:
bla bla (y
y) bla bla
preg_match('/\((.*?)\)/si', $varx, $match);
A better expression can be constructed if the content between paraentheses has a regular pattern. For example, if it were always double letters like xx or yy, the following expression would be a better match.
/\(([a-zA-Z]{2})\)/i
Also, if you want to capture all matches in $varx
, use preg_match_all()
. For example:
this (and) that (or) the other
preg_match_all()
will capture and
and or
To test it use something like:
<?php
$varx = "this (and) that (or) the other";
preg_match_all('/\((.*?)\)/si', $varx, $matches);
print_r($matches);
?>
This will show where the matches are in the $matches
array.
I hope this works
preg_match_all('#\(((?>[^()]+)|(?R))*\)#x');
I'm sorry for the incomplete answer..
$preg_match = '#\(((?>[^()]+)|(?R))*\)#x'; $data = 'bla bla (yy) bla bla'; if(preg_match_all($preg_match, $data, $match)) { $match = $match[0]; } else { $match = array(); }
Hope is makes sense now
This seems cleaner.
$pattern = '/\((.+?)\)/is';
Do not use regex for this, use str_replace()
$string = str_replace(array('(', ')'), '', $your_string);
精彩评论