But this method will not detect mistake like this:
Because counting makes sense only if you want to check if there's equal number of opening and closing brackets. But if you want to be kind to your user and point to the place he made a mistake, then counting will not be sufficient and you should use i.e. the stack (even array based stack based on array_push()
and array_pop()
would suffice). With stack you iterate over your string and push a token when you encounter opening bracket <
and pop a token when you hit closing one >
. In your case:
This is >b<BOLD>/b< word
you would have to do pop
as first is >
but there's nothing on stack so this triggers error. Let's fix that bracket and continue:
This is <b<BOLD>/b< word
and run
push -> ok
push -> well if you allow nested brackets, then all is ok, otherwise
stack must be empty prior pushing so this bracket is misplaced
and you shall throw an error
and so on... and once you reach end of the string and your stack is not empty then you know last spotted <
misses its >
pair (If you allow bracket nesting, then logic needed to tell which one is potentially not closed may be more complicated and sometimes give false results (as compilers sometimes do in similar case for example)).
If you do not plan to allow nested brackets, then you can make your code even simpler as using plain integer
variable to indicate the state would suffice (i.e. '0' for <
, 1
for >
and -1
for initial state)