I'm trying to cast string to int. Everything work fine but have a small problem here
echo (int)"--12"; //return 0, i want 12
echo (int)"---23";//return 0, i want -23
echo (int)"+-99"; //return 0, i want -99
...
Why did this happened and what is the right way to cast in this case? Many thanks!
To evaluate the positive and negative signs so that all positive symbols are ignored and two negatives equal a positive, you can perform a replacement.
Code: (Demo)
$signed_number_strings = ["--1", "---33", "+-444"];
foreach ($signed_number_strings as $string) {
var_dump((int)preg_replace('~\++|-\+*-\+*~', '', $string));
}
Output:
int(1)
int(-33)
int(-444)
The logic behind the pattern is to first match/remove 1 or more consecutive +
signs, OR a -
sign followed by zero or more +
followed by a -
(and absorbing any trailing +
signs). If there are any fringe cases that my pattern doesn't correctly handle, please update your question and leave me a comment.
p.s. The extension of my 2nd branch with \+*
is an attempt to optimize the pattern so that it doesn't have to restart the pattern. It could have been written as ~\++|-\+*-~
which would be slightly less strain on the eyeballs. (Demo)
you can extract number from string . can help?!
$str = '--1';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);
I am not 100% sure on your use case but I knocked up this function to try and handle a string with numbers and to return the first full number with negative signed support.
I am sure I have your use case wrong but you can butcher this function however you like to drop the negative signed handling or to possibly handle floats where a decimal place may be needed for detection.
Worth noting that a regex may even exist for this.. who knows.
function intvaljunk($string) {
$boolSignedNegative = false;
$intIntStart = null;
$intIntEnd = null;
foreach (str_split($string) as $index => $char) {
if (is_numeric($char)) {
$boolSignedNegative = (
$boolSignedNegative === false
&& $index > 0
&& is_null($intIntStart)
&& $string[$index - 1] === '-'
? true
: $boolSignedNegative
);
$intIntStart = is_null($intIntStart) ? $index : $intIntStart;
$intIntEnd = is_null($intIntStart) ? $intIntEnd : $index;
} else if (!is_null($intIntStart) && !is_null($intIntStart)) {
break;
}
}
return (
!is_null($intIntStart) && !is_null($intIntStart)
? intval(($boolSignedNegative ? '-' : '') . substr($string, $intIntStart, ($intIntEnd - $intIntStart) + 1))
: null
);
}
echo intvaljunk("--1") . PHP_EOL;
echo intvaljunk("---1") . PHP_EOL;
echo intvaljunk("+-1") . PHP_EOL;
echo intvaljunk("+-14991abc667") . PHP_EOL;