Reputation: 39628
There are a lot of questions on removing leading and trailing 0s but i couldn't find a way to remove all 0s except trailing 0s (leading 0 or in any other place other than the end).
100010 -> 110
010200 -> 1200
01110 -> 1110
any suggestions ?
Upvotes: 0
Views: 193
Reputation: 197775
You want to replace all zeroes that are not at the end of the string.
You can do that with a little regular expressions with a so called negative look-ahead, so only zeros match to be replaced that are not at the end of the string:
$actual = preg_replace('/0+(?!$|0)/', '', $subject);
The $
symbolizes the end of a string. 0+
means one or more zeroes. And that is greedy, meaning, if there are two, it will take two, not one. That is important to not replace at the end. But also it needs to be written, that no 0 is allowed to follow for what is being replaced.
Quite like you formulated your sentence:
a way to remove all 0s except trailing 0s (leading 0 or in any other place other than the end).
That is: 0+(?!$|0)
. See http://www.regular-expressions.info/lookaround.html - Demo.
The other variant would be with atomic grouping, which should be a little bit more straight forward (Demo):
(?>0+)(?!$)
Upvotes: 1
Reputation: 12776
You can use regexes to do what you want:
if(preg_match('/^(0*)(.*?)(0*)$/',$string,$match)) {
$string = $match[1] . str_replace('0','',$match[2]) . $match[3];
}
Upvotes: 0
Reputation: 288
here is a solution. there shoud be prettier one, but that works also.
$subject = "010200";
$match = array();
preg_match("/0*$/",$subject,$match);
echo preg_replace("/0*/","",$subject).$match[0];
Upvotes: 0
Reputation: 1984
// original string
$string = '100010';
// remember trailing zeros, if any
$trailing_zeros = '';
if (preg_match('/(0+)$/', $string, $matches)) {
$trailing_zeros = $matches[1];
}
// remove all zeros
$string = str_replace('0', '', $string);
// add trailing ones back, if they were found before
$string .= $trailing_zeros;
Upvotes: 0
Reputation: 12721
You can use regex as others suggested, or trim. Count the trailing 0's, strip all 0's, then add the trailing 0's back.
$num = 10100;
$trailing_cnt = strlen($num)-strlen(trim($num, "0"));
$num = str_replace('0','',$num).str_repeat('0', $trailing_cnt);
Upvotes: 0
Reputation: 39532
You can use the regex [0]+(?=[1-9])
to find the zeros (using positive lookahead) and preg_replace
to replace them with an empty string (assuming the number is already in string form).
$result = preg_replace("#[0]+(?=[1-9])#", "", "100010");
See it in action here
Upvotes: 2
Reputation: 5605
Not the prettiest but it works...
$str = "01110";
if(substr($str,-1) == 0){
$str = str_replace("0","",$str)."0";
}else{
$str = str_replace("0","",$str);
}
echo $str; // gives '1110'
Upvotes: -1