简体   繁体   English

您如何在PHP中的每个字符中回显字符串?

[英]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. 我需要知道PHP中是否有一种方法可以在每个字符中回显字符串。

For instance 例如

/n

and the likes. 等等。


Edit for clarification : 编辑以澄清问题

When I have a webform and I submit it and I have this text: 当我有一个Web表单并提交它时,我有以下文本:

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. 我希望能够打印以筛选每个特殊字符,例如/ 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'. 我认为他的意思是,当字符串包含“ \\ n”时,他不想看到换行符,而是希望将“ \\ n”看成两个字符,即“ \\”和“ n”。

json_encode works well for this purpose: json_encode可以很好地实现此目的:

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: 假设您要在每个字符上添加\\ n,并且$string包含要编辑的字符串:

$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. 此$ string之后将包含原始$ string,并在每个字符后添加换行符,并将其回显。 For this to be displayed, you'd have to surround it with <pre> though. 要显示此内容,您必须用<pre>包围它。

I think he wants to break string into chars and want to print each char in new line. 我认为他想将字符串分解为字符,并希望在新行中打印每个字符。 is it ? 是吗 ?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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