Now that I have a better understanding of what you're trying to do here, I think a more robust solution would be better. For example, see http://stackoverflow.com/a/925630/72321. For a similar but even better solution (and solutions for similar problems), see what Django uses: https://github.com/django/django/blob/master/django/utils/html.py.