View Full Version : Seeing special characters

09-07-2011, 09:43 PM
I was just working with a string that I needed to break on new lines into array values (used preg_split for it), and initially, I just broke on \n, which actually lead to the artifact of having a hidden \r remaining I didn't notice. Upon echoing the variables, I saw a space, and wondered how it got in there. After a bit of thought, I realized that was the \r I couldn't see.

I know I could have used trim to get rid of the problem in the first place, but I'm curious: is there a way to have new characters show up? I tried addslashes to no avail. There are ways to avoid the issue of course, but just for my own information, I'm wondering if anyone has a method I could use?

09-07-2011, 10:04 PM
The only way that makes sense for this is to walk the string array through a ord() call character by character. \r = 0xD and \n = 0xA. Knowing this you could replace it then with \ + r and \ + n, which could actually be done using an str_replace now that I think of it.

09-13-2011, 07:02 PM
Sorry, a bit of a necro, and I apologize, as I forgot I asked this...

so I can have str_replace search for the hex values of the characters? I need to find a chart, I don't remember hex values anymore :(

09-13-2011, 10:00 PM
If you just want newlines and carriage returns visible you can do something like this:

$myString = "Some text\r\nmore text";
echo str_replace(array("\r", "\n"), array('\r', '\n'), $myString);
That will output:

Some text\r\nmore text

09-14-2011, 12:48 AM
Awesome, thanks!

09-14-2011, 12:56 AM
Yep, I've been kinda busy myself.
I was thinking the only way to do it is to ord it and compare, and then I had the after thought of simply replacing "\r\n" with '\r\n', as demonstrated by Inigoesdr.