Preparing PHP for JavaScript
Isn’t it amazing what can stump you when you busy programming. I was working on getting a discussion forum thread to appear in a tree format, and in doing so, had to ‘clean’ up the text.
The steps I took was:
- Strip HTML Tags – strip_tags()
- Take the first 50 letters of the post - substr()
It worked well, except for one thread – which for some reason just wasn’t displaying at all and giving javascript errors. The PHP function ought to work, and was working in all the other cases.
The problem…
I got alerted to this by reading one of the user notes in the PHP manual. PHP’s functions do not clean the unicode line break \r \n, so you have to this manually. Else when you echo your javascript, the line breaks will appear, effectively messing it up.
A quick way of cleaning up the line breaks are:
$text = preg_replace("/(\r\n|\n|\r)/", "", $text);
