从字符串到int的转换不起作用


Conversion from string to int does not work

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

当然,通常我会说

$distance=intval($distance);

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

这就是我所做的:

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

正则表达式是正确的,如果我回显$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);

如果您执行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
        )
)

在零之前必须有一个空格,或者可能有一个0xA0字节。在正则表达式中使用"''d"以确保获得数字。

编辑:您可以使用清除值

$value = (int)trim($value, " 't'r'n'x0B'xA0'x00");

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

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

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