开发者

php trim won't work

So I have a server side aj开发者_JAVA技巧ax php file:

$thing = "\n\ncode\n";
echo(trim($thing, '\n'));

php trim won't work

But when I use this php file for an ajax call, the responseText does not have newlines removed!

php trim won't work

var xhr7 = new XMLHttpRequest();
xhr7.onreadystatechange = function() {
  if (xhr7.readyState == 4) {
    if (xhr7.status == 200) {
      alert('trying');
      alert(xhr7.responseText);
      chrome.tabs.executeScript(null, {code: xhr7.responseText });
    } else {
      alert("404 server side ajax file DOES NOT EXIST");
    }
  }
};
xhr7.open('POST', 'http://texthmu.com/Devin/HMU%20ext/Post-jsfile-forItsCode.php', true);
xhr7.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //following w3 
xhr7.send(); `


\n needs to be in double quotes not single

echo(trim($thing, "\n"));

When a value is in single quotes, it's parsed as a literal. In this case \n instead of the new line character you're trying to trim.


You need to place the \n character in a double quoted (") string.

PHP doesn't interpet these special characters in single quote (') delimited strings.


Just use

$thing = "\n\ncode\n"; 
echo(trim($thing));

Ref: http://php.net/manual/en/function.trim.php

This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.
  • "\t" (ASCII 9 (0x09)), a tab.
  • "\n" (ASCII 10 (0x0A)), a new line (line feed).
  • "\r" (ASCII 13 (0x0D)), a carriage return.
  • "\0" (ASCII 0 (0x00)), the NUL-byte.
  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

Additional for the comments below

Please note that;

$thing = "\n\nco\nde\n"; // See the \n between co and de ? 
echo(trim($thing, "\n"));

If you wish that it be removed too, then trim is not the right function for you.

If you wish to remove ALL \n from a string, then you should use

str_replace("\n", "", $thing);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜