从字符串转换为int不起作用

时间:2012-08-20 16:59:44

标签: php int type-conversion

我使用正则表达式从文档中获取值并将其存储在名为$distance的变量中。这是一个字符串,但我必须将它放在数据库中表的int列中。

当然,通常我会去说

$distance=intval($distance);

但它不起作用!我真的不知道为什么。

这就是我正在做的事情:

preg_match_all($regex,$content,$match);
$distance=$match[0][1];
$distance=intval($distance);

正则表达式是正确的,如果我回显距离,它就是例如“0” - 但我需要它为0而不是“0”。使用intval()会以某种方式将其转换为空字符串。

编辑1

正则表达式是这样的:

$regex='#<value>(.+?)</value>#'; // Please, I know I shouldn't use regex for parsing XML - but that is not the problem right now

然后我继续

preg_match_all($regex,$content,$match);
$distance=$match[0][1];
$distance=intval($distance);

3 个答案:

答案 0 :(得分:1)

在零之前必须有一个空格,或者可能(在那里,已经完成)0xA0字节。在你的正则表达式中使用“\ d”以确保获得数字。

编辑:您可以使用

清理值
$value = (int)trim($value, " \t\r\n\x0B\xA0\x00");

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

答案 1 :(得分:1)

如果您print_r($match),您会看到所需的数组是$match[1]

$content = '<value>1</value>, <value>12</value>';

$regex='#<value>(.+?)</value>#';

preg_match_all($regex,$content,$match);

print_r($match);

输出:

Array
(
    [0] => Array
        (
            [0] => <value>1</value>
            [1] => <value>12</value>
        )

    [1] => Array
        (
            [0] => 1
            [1] => 12
        )

)

在这种情况下:

$distance = (int) $match[1][1];

var_dump($distance);

输出:int(12)


或者,您可以使用PREG_SET_ORDER标志,即preg_match_all($regex,$content,$match,$flags=PREG_SET_ORDER);,$ match数组具有以下结构:

Array
(
    [0] => Array
        (
            [0] => <value>1</value>
            [1] => 1
        )

    [1] => Array
        (
            [0] => <value>12</value>
            [1] => 12
        )

)

答案 2 :(得分:0)

为什么你的正则表达式中需要问号?试试这个:

$regex='#<value>(.+)</value>#';
相关问题