I have something like:
$string1="dog fox [cat]"
I need the contents inside [ ] i.e cat
another question: if you are familiar with regex in one language, will it do for the other languages as well?
I have something like:
$string1="dog fox [cat]"
I need the contents inside [ ] i.e cat
another question: if you are familiar with regex in one language, will it do for the other languages as well?
$matches = array();
$matchcount = preg_match('/\[([^\]]*)\]/', $string1, $matches);
$item_inside_brackets = $matches[1];
If you want to match multiple bracketed terms in the same string, you'll want to look into preg_match_all
instead of just preg_match
.
And yes, regular expressions are a fairly cross-language standard (there are some variations in what features are available in different languages, and occasional syntax differences, but for the most part it's all the same).
Explanation of the above regex:
/ # beginning of regex delimiter
\[ # literal left bracket (normally [ is a special character)
( # start capture group - isolate the text we actually want to extract
[^\]]* # match any number of non-] characters
) # end capture group
\] # literal right bracket
/ # end of regex delimiter
The contents of the $matches
array are set based on both the entirety of the text matched (which would include the brackets) in [0], and then the contents of each capture group from the matching in [1] and up (first capture group's contents in [1], second in [2], etc).
Here is the php code:
preg_match('/\[(.*)\]/', $string1, $matches);
echo $matches[1];
And yes, your knowledge will transfer. Although there my be subtle differences between each language's version of regular expressions.