I want to use the htmlentites() method, but I don't want the method to change the input ONLY FOR the tag "<br>", and the phrase " " I will take code alternate to htmlentities(), so long as it will not compromise security.
I want to use the htmlentites() method, but I don't want the method to change the input ONLY FOR the tag "<br>", and the phrase " " I will take code alternate to htmlentities(), so long as it will not compromise security.
unfortunately, htmlentities() will not discriminate between types of tags. This should work:
This works by finding the phrases '<br>' or ' ' (case insensitive) and replacing them with the html encoded equivalents for any string or array of strings input.Code:function ReplaceBR_NBSP(input_str) { return str_ireplace(array('<br>',' '),array('<br>','&nbsp;'),input_str); }
hope this helps!![]()
Last edited by garrettroyce; 02-23-2009 at 07:11 PM. Reason: forgot [/code]
gjr.gr - coming soon: secrets of OCD coding from a self taught tinkerer
I'm intrigued...
What is the str_ireplace function?
I would have just used
str_replace('<br'>, '<br>');
str_replace(' ', '&nbsp;');
str_ireplace is the same as str_replace, except it ignores case (ie "<br>" and "<BR>" would both be replaced). Most string functions have a counterpart that ignores case, that's what the "i" stands for.
I don't know how experienced you are with PHP, so this explanation may be a little confusing: str_replace can accept arrays for arguments as well as strings. If you give it an array, it will work through each element and replace it like normal. Check the function reference page: http://us2.php.net/manual/en/function.str-ireplace.php . Your code and garret's will do the same thing. I'll rewrite his code so it's easier to visualize:
PS - I reread your post, do you want to convert everything to html entities EXCEPT "<br>" and " ", or ONLY those two strings, because that function will replace ONLY those two. If you want it the other way around, do $input_str = htmlentities($input_str), then switch $search and $replace. That way, it will convert everything, then revert line breaks and spaces to the way they were before.Code:function ReplaceBR_NBSP($input_str) { $search[0] = '<br>'; $search[1] = ' '; $replace[0] = '<br>'; $replace[1] = '&nbsp;'; return str_ireplace($search, $replace, $input_str); }
Last edited by Spasm; 02-24-2009 at 10:09 AM.
Good call, Spasm.
gjr.gr - coming soon: secrets of OCD coding from a self taught tinkerer
I'll give you reputation (first reply) because it was helpful, but I was actually looking for the reverse. I want to replace the '&nbsp;' with ' ', not the other way around. But I can use the same method.
Thanks for the help on this. I am not particularly experienced with php but know enought to understand the array point.
The "i" prefix with be very useful for other projects!