tags:

views:

114

answers:

2

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?

+5  A: 
$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).

Amber
Don’t use the non-greedy quantifier when you can use a negated character class. `/\[([^\]]*)\]/` is a better regular expression for this case.
Gumbo
thanks for the explanation
Karthik Kottapalli
@Gumbo - good point, and I agree. I'll update the regex.
Amber
Quite surprised he didn't pick yours, +1 from me though
Cryo
It is working pretty well. But I am getting undefined offset error for strings that don't have [ ] How to eliminate the offset?
Karthik Kottapalli
Check the the count of matches is greater than 0.if(count($matches) > 0) {}
smack0007
Or just check the return value from `preg_match`, which my example code above already stores in `$matchcount`.
Amber
yeah that fixed it. Thanks a lot :-)
Karthik Kottapalli
A: 

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.

smack0007
I don't feel like my answer was the best...
smack0007