You are probably trying to solve the wrong problem. (I know this is not what you want to hear.)
If users are allowed to write unencoded >>
and <<
into HTML then presumably they would also be able to write <>
or <b>
, and in that case there is no way you can reliable distinguish between text and markup. (Never mind that this makes you vulnerable to XSS attacks.)
You really have to intercept the text and encode it before it is interpolated into HTML. Probably you should explain the workflow leading to you problem. There must be a better way to solve it.
Edit in response to comment: There is simply no way to reliably encode input which can be either text or HTML at the same time. Anyway, if users are technical enough to enter raw HTML, presumably they are able to write entities - otherwise the shouldn't be entering raw HTML in the first place. If HTML input is only for advanced users, then you could have a check-box which indicated if the input is text or HTML. But you should probably look into using a rich-text editor.