I'm looking for a solution to find if a :-char is enclosed by [ and ] or not.
I have a sort of syntax which enables to define keys with corresponding values in a template. The syntax is exploded by :-char to identify the keys, but a :-char should also be valid if it's within the brackets. Basically my sample/case is like:
:key1[value]:key2[this:value should work too]
.
I'm looking for a way to find if :-char is within the brackets. I've started writing out a procedure to figure this out, but somewhere during the writing an electronic pulse in my mind said 'regex.. regex'. But I'm quite unfamiliar with them. Could someone help me out?
P.s. if you're downvoting the question, at least tell me why you think its a bad question. In my opinion its a correct question I'm asking assistance for.
I'm gonna show you the general way to parse this: DEMO
:(key\d)+\[([^\]]+)\]
What you need to do is match everything between [
and ]
so instead of using .*
you must tell the Regular Expression that you want to MATCH EVERYTHING that is not ]
so... [^\]]
You can see the demo for more explanation.
preg_match('~\[[^\]]*:~', $str)
this will return 1
if there is a :
char within brackets. The regex assumes the brackets are always paired.
To find whether :-char is within [] it is enough to put in your regexp following:
preg_match('/\[:-char\]/', $string);
This will match all ":-char" wrapped with [ ]. Please note that [ ] chars are part of regexp pattern and hence should be escaped. If you want to find all ":-char", but see whether it has [ ] or not, then you go for
preg_match('/(\[)?:-char(\])?/', $string, $var);
Then result of everything in ( ) will be captured into $var
. And from the structure of it you can judge whether it was wrapped with [ ] or not
For better understanding how regular expressions work i would suggest standard PHP documentation: http://php.net/manual/en/book.pcre.php