【问题标题】:string and integer sum calculate in php?字符串和整数和在php中计算?
【发布时间】:2020-12-21 08:50:09
【问题描述】:
<?php
    $a = '32abc';
    $b = 1;
    echo $a + $b;

    Output : 33
?>

这里字符串$a = '32abc';用int计算$b = 1,如何从php中的字符串word中取32。并输出显示 33 。有什么好的解释吗?

【问题讨论】:

标签: php string sum numbers


【解决方案1】:

尝试使用运算符intval 从字符串中提取整数。 但只有在字符串开头为 int 时才有效。

    $a = intval('32abc');
    $b = 1;
    echo $a + $b;

【讨论】:

  • intval() 与从字符串中提取数字无关,您看到的行为定义为 here
【解决方案2】:

尝试 preg_replace 只允许数字,像这样:

<?php

$a = '32abc'; 
$b = 'abc1';
$c = '1abc1';
$d = 6;

echo preg_replace('/[^0-9.]+/', '',   $a) + preg_replace('/[^0-9.]+/', '',   $b) + preg_replace('/[^0-9.]+/', '',   $c) + $d;

?>

将回显 50 (32 + 1 + 11 + 6)

你也可以做一个函数,像这样:

echo removeCharsFromString($a) + removeCharsFromString($b) + removeCharsFromString($c) + $d;

function removeCharsFromString(string $inputString) {
    return (int) preg_replace('/[^0-9.]+/', '',   $inputString);
}

【讨论】:

    猜你喜欢
    • 2015-10-05
    • 1970-01-01
    • 2016-10-21
    • 2015-03-14
    • 2016-04-17
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    • 2017-06-10
    相关资源
    最近更新 更多