简体   繁体   中英

How do you echo a string with every char in PHP?

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.

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"

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM