为什么空格会在PHP中导致致命错误? [英] Why would whitespace cause a fatal error in PHP?

查看:155
本文介绍了为什么空格会在PHP中导致致命错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关联数组,出于所有意图和目的,出现似乎绝对没有理由甚至发出警告.整个源代码如下:

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:

解析错误:语法错误,意外的T_ARRAY, 5 行中的/Applications/MAMP/htdocs/wtf2.php 中的')' >

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

我仔细看了一下,然后发现在第4行上似乎有一个或两个尾随空格(起初我什至没有三思而后行).但是,当我复制空白时,将其粘贴到新文档中,如下所示(第2行):

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

问,那是怎么到达那里的?"但是我真的不认为这是一个可行的问题.所以我的实际问题是:这样的空格与其他任何空格有何不同(尤其是在通过PHP解释器运行时会导致致命错误的地步)?有没有办法防止将来发生这种情况?

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:我正在运行5.3.20版的PHP(通过Mac上的MAMP Pro).

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

PPS:为明确起见,在删除白空间自身时,代码运行良好.

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

推荐答案

您所拥有的是一个UTF-8编码的不间断空格(%C2%A0,又名&nbsp;),它破坏了PHP的解析器. PHP的一个已知问题被标记为无法解决",因为人们可能将此字符用作标识符的一部分".请参见请求#38766不间断空格会导致解析失败.

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.

这篇关于为什么空格会在PHP中导致致命错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆