Why would whitespace cause a fatal error in PHP?

拜拜、爱过 提交于 2019-12-10 10:25:19

问题


I have an associative array that, for all intents and purposes, appears to have absolutely no reason to throw even a warning. The entirety of the source code is as follows:

<?php
$entries = array(
  array('date' => '2012-08-12', 'change' => '-19'),
  array('date' => '2012-08-13', 'change' => '-21'),  
  array('date' => '2012-08-14', 'change' => '-19'),
  array('date' => '2012-08-15', 'change' => '-17'),
);
foreach ($entries as $entry) {
  print $entry['date'] . ': ' . $entry['change'] . '<br/>'; 
}

To me everything looks fine, however when I go to view the output in my browser, I get the following error message:

Parse error: syntax error, unexpected T_ARRAY, expecting ')' in /Applications/MAMP/htdocs/wtf2.php on line 5

I looked a little closer and then discovered that on line 4, there was what appeared to be a trailing space or two (which I didn't even think twice about, at first). However when I copied the whitespace, pasted it into a new document like so (line 2):

<?php
$whitespace = '  ';
print rawurlencode($whitespace);

... and then viewed the output in my browser, this is what I saw:

%C2%A0%20

I would ask, "How did that get there in the first place?" but I don't really think that's a feasible question to answer. So my actual question is this: how does whitespace like that differ from any other whitespace (especially to the point where it causes a fatal error when ran through the PHP interpreter)? And is there a way to prevent this from happening in the future?

PS: I'm running PHP version 5.3.20 (via MAMP Pro on a Mac).

PPS: To clarify, WHEN THE WHITESPACE ITSELF IS DELETED, THE CODE RUNS FINE.


回答1:


What you have there is a UTF-8 encoded non-breaking space (%C2%A0, aka &nbsp;), which breaks PHP's parser. It's a known problem with PHP that is marked as "won't fix" because people "might use this character as part of an identifier." See Request #38766 Nonbreaking whitespace breaks parsing.




回答2:


just banged my head for about an hour going totally insane about this.

Notepad++ doesn't show ANY difference between a regular space and a nbsp.

If you wonder how this character actually got into your code, this is how i got mine : altgr + space



来源:https://stackoverflow.com/questions/17461759/why-would-whitespace-cause-a-fatal-error-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!