string and integer sum calculate in php?
Solution:
Try operator intval
for extract int from string.
But work only if int in the start of string.
$a = intval('32abc');
$b = 1;
echo $a + $b;
Answer
Solution:
Try preg_replace to allow only numbers, so like this:
<?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;
?>
will echo 50 (32 + 1 + 11 + 6)
You could also make a function and do it like:
echo removeCharsFromString($a) + removeCharsFromString($b) + removeCharsFromString($c) + $d;
function removeCharsFromString(string $inputString) {
return (int) preg_replace('/[^0-9.]+/', '', $inputString);
}
Source