In PHP when we do a substr()
such that the resultant string should be something like 0004
, PHP automatically removes the leading 0
s and just gives 4
.
I want to avoid this behavior. I want the leading zeroes to stay there. How can I enforce that?
Forexample the following snippet prints 4
.
echo substr("100041", 1, 4);
How can I force it to print 0004
?
Anyway create a own function..
<?php
function substring($data,$from,$length){
$sub = "";
$data = str_split($data);
$i = 0;
$l = 1;
foreach($data as $letter){
if($i >= $from && $l <= $length){
$sub .= $letter;
$l = $l+1;
}
$i = $i+1;
}
return $sub;
}
echo substring("100041", 1, 4);
?>
It doesn't:
var_dump(substr("100041", 1, 4));
string(4) "0004"
As per documentation this is a 100% string function. It doesn't handle numbers in any special way.