duanmian1085 2014-05-07 22:46
浏览 18
已采纳

PHP explode()和If语句

I literally spent 6 hours trying to find this out. I have the code below:

$pieces3 = explode(":", $value2);
$checkiftime = $pieces3[0];
if ($checkiftime == 'time')
{
echo "Yes!";
}
else
{
echo "Oh no!";
}

$value2 contains:

" 'time': 1376952971"

I'm pretty sure the statement should be true but for some reasons, I keep getting false (oh no!)

if ($checkiftime == 'time')

What could be wrong? I already tried using double quotes for $checkiftime=="time" but still no avail.

EDIT:

I tried doing Vardumps after the explode:

var_dump($pieces3);
echo "<br>";
var_dump($value2);
echo "<br>";
var_dump($pieces3[0]);
echo "<br>";

And resulted with:

array(2) { [0]=> string(13) " 'time'" [1]=> string(11) " 1376952971" } 
string(25) " 'time': 1376952971" 
string(13) " 'time'" 

I'm not sure why 'time' shows as String(13), I see that blank space, could that be a special character containing more than 1 hidden string? I did a trim() but it doesn't seem to change anything.

EDIT2:

Thanks everyone, below is the part of the code that I modified and it worked great:

$checkiftime = trim($pieces3[0], " '\t
\0\x0B");
if ($checkiftime == 'time')
  • 写回答

5条回答 默认 最新

  • duanmei1930 2014-05-08 02:56
    关注

    I guess the main problem is that $value2 contained an unexpected value.

    It simply looks like you need to sanitise the string, removing any characters that might get in the way of your check (such as space and apostrophe / single-quote). Try this...

    $checkiftime = trim($pieces3[0], " '\t
    \0\x0B");
    

    See trim(). Demo here - http://ideone.com/uVEDXM

    Alternatively, you could simply use a regular expression match to check the entire string, eg

    if (preg_match('/^\W*time\W*: (\d+)$/', $value2, $matches)) {
        echo 'Yes!', PHP_EOL;
        var_dump($matches); // $matches[1] contains the numeric value 1376952971
    }
    

    Demo - http://ideone.com/025vAV

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应