【问题标题】:Php display as a html text the new line \nphp 显示为 html 文本的新行 \n
【发布时间】:2014-09-12 09:01:13
【问题描述】:

我正在使用 echo 显示结果,但结果包含换行符 /n /t /r。

我想知道结果是 \n 还是 \t 或 \r 以及有多少。我需要知道,所以我可以将其替换为 html 标记,例如 <p><div>

结果来自其他网站。

In pattern CreditTransaction/CustomerData: 



        Email does not contain any text

In pattern RecurUpdate/CustomerData:      



    Email does not contain any text

In pattern AccountInfo: 

我想要这样。

In pattern CreditTransaction/CustomerData: 
    \n
    \n
    \n  
      \n\tEmail does not contain any text
      \n
In pattern RecurUpdate/CustomerData:      
    \n
    \n
      \n
    \n\tEmail does not contain any text

\n\tIn pattern AccountInfo: 

【问题讨论】:

  • 这可能对nl2br有帮助
  • 是的,我已经尝试过了,但只显示 br 标签。我怎么知道是 /t 还是 /n?
  • 与其需要知道,为什么不直接使用带有字符数组及其替换的str_replace()
  • t 不是一个标签吗? r 是新行的口头表示。
  • 您需要哪种方式?你说你需要知道所以你可以用html标签替换它,但是你想要的结果包含\n\t?

标签: php html line-breaks pre


【解决方案1】:

您的问题很不清楚,但我会尽力提供答案。

如果您想让 \n、\r 和 \t 在输出中可见,您可以手动取消转义它们:
str_replace("\n", '\n', str_replace("\r", '\r', str_replace("\t", '\t', $string)));

或者,如果您想取消转义所有转义字符:
addslashes($string);

计算特定字符/子字符串出现的次数:
substr_count($string, $character_or_substring);

检查字符串是否包含特定字符/子字符串:
if (substr_count($string, $character_or_substring) > 0) { // your code }
或:
if (strpos($string, $character_or_substring) !== false) { // notice the @987654321@ // your code }

正如前面其他人在评论中提到的,如果要将换行符转换为 br 标签:
nl2br($string);

如果你想让制表符缩进,你可以用 替换所有制表符:
str_replace("\t", ' ', $string);

【讨论】:

  • str_replace("\n", '\n', str_replace("\r", '\r', str_replace("\t", '\t', $string)));这是我正在寻找的谢谢。
【解决方案2】:

使用双引号查找换行符和制表符。

$s = "In pattern CreditTransaction/CustomerData: 



    Email does not contain any text

  In pattern RecurUpdate/CustomerData:  ";

echo str_replace("\t", "*", $s);  // Replace all tabs with '*'
echo str_replace("\n", "*", $s);  // Replace all newlines with '*'

【讨论】:

    猜你喜欢
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 2011-09-03
    • 1970-01-01
    • 2016-04-04
    • 2013-11-11
    • 1970-01-01
    相关资源
    最近更新 更多