tags:

views:

192

answers:

3

I need to know if there's a way in PHP to echo a string with every char.

For instance

/n

and the likes.


Edit for clarification:

When I have a webform and I submit it and I have this text:

I am stupid
and I cannot
explain myself

The text would be like this:

I am stupid /n and I cannot /n explain myself

If I use:

nl2br

I get:

I am stupid <br /> and I cannot <br /> explain myself

Now I have users that input some messed up texts and I need to clean it and put it inside an array. I would love to be able to print to screen every special char such as /n.

A: 

Assuming you mean to add \n to every character and $string contains the string you want to edit:

$strarray = str_split($string);
$string = "";
foreach($strarray as $char)
{
    $string .= $char."\n";
}
echo $string;

After this $string will contain the original $string with a newline added after every character, and will be echoed. For this to be displayed, you'd have to surround it with <pre> though.

Arda Xi
$i=0; while isset($string[$i]) echo $string[$i++]."\n"; But it isn't what he asked :)
Col. Shrapnel
+3  A: 

I think he means that instead of seeing a newline when a string contains '\n' he wants to see the '\n' as two characters, a '\' and an 'n'.

json_encode works well for this purpose:

echo json_encode("spam\nand eggs");
>> "spam\nand eggs"
thetaiko
but he wants other characters to be escaped. And, I suspect, not only C-style escapes
Col. Shrapnel
Indeed he does. `addcslashes` is just an option. `json_encode` will, I believe, return everything OP needs, if this is, in fact, what OP was looking for.
thetaiko
My answer updated to remove `addcslashes` which works for specific lists of characters that you provide.
thetaiko
Thank you, exactly what I was looking for. I don't know how you managed to understand my question ;-)
0plus1
A: 

I think he wants to break string into chars and want to print each char in new line. is it ?

NAVEED