【问题标题】:Clearing CR CL and spaces in PHP string清除 PHP 字符串中的 CR CL 和空格
【发布时间】:2017-09-04 09:24:31
【问题描述】:

我在尝试使用该字符串时遇到问题,当我将其复制到记事本++ 并查看所有字符选项卡时,它显示了以下附加符号。我的知识是它们是换行符和空格。问题是,我似乎无法将它们从我的字符串中删除?

解释:

我有一个函数,它使用 shell_exec 从存储的数据库中获取信息。

$output = trim(shell_exec("'".$command."' 2>&1")); //Trimmed version
return $output;

我有一个信用系统,但是当他们加载页面时,它会根据用户等调用函数来获取信用。

$Credits = Sqlite('select "Credits" from TBL WHERE User = "bla" limit 1');

事情是,信用回来了,旁边有一个。所以如果我存储了9.50,我收到了�9.50。在查看此内容时,我注意到字符串中包含上述字符?

我的 PHP 尝试:

$Credits = preg_replace('/\s/', '', $Credits); //Clear all spaces
//$Credits = str_replace(' ', '', $Credits); //Clear spaces <-- dont work either
$Credits = str_replace('\r\n', '', $Credits); //Clear all new lines
echo $Credits; //Still returns the new line etc

【问题讨论】:

  • 请发帖MCVE (minimal complete verifiable example)$Credits = preg_replace('/\s/', '', $Credits); 应该可以完成这项工作。好吧,如果有 Unicode 字符,你需要'/\s/u',但这里似乎不是这样。另外,为什么不试试trim()
  • 为什么要删除这些字符?
  • 顺便说一句。你应该使用"\r\n" 而不是'\r\n' - 转义序列只能在带有" 的字符串中工作
  • 我用更好的解释更新了答案! :)
  • 尝试找出错误字符的来源并修复它。您的 SQlite 数据库似乎是罪魁祸首。

标签: php preg-replace str-replace


【解决方案1】:

$Credits 只是一个变量,不会改变文件的上下文。所以试试这个:

<?php
$text = file_get_contents('source.txt');
echo '<pre>'; // to display any new line from linebreak
echo $text;

echo '<br>====<br>';

$text = preg_replace('/\r\n/','a',$text); // a is just an indicator of original linebreak which you can use '' empty instead

echo $text // display text after linebreak is replaced from variable $text
file_put_contents('source2.txt', $text); // save this to file with linebreaks removed
// or replace content of source.txt
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多