Remove all 0s except trailing 0s from a string - php

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 ?

Try
echo preg_replace('/0+([1-9])/', '$1', $str);

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

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+)(?!$)

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);

// 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;

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];

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];
}

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'

Related

How can remove the numberic suffix in php?

For example, if I want to get rid of the repeating numeric suffix from the end of an expression like this:
some_text_here_1
Or like this:
some_text_here_1_5
and I want finally receive something like this:
some_text_here
What's the best and flexible solution?
$newString = preg_replace("/_?\d+$/","",$oldString);
It is using regex to match an optional underscore (_?) followed by one or more digits (\d+), but only if they are the last characters in the string ($) and replacing them with the empty string.
To capture unlimited _ numbers, just wrap the whole regex (except the $) in a capture group and put a + after it:
$newString = preg_replace("/(_?\d+)+$/","",$oldString);
If you only want to remove a numberic suffix if it is after an underscore (e.g. you want some_text_here14 to not be changed, but some_text_here_14 to be changed), then it should be:
$newString = preg_replace("/(_\d+)+$/","",$oldString);
Updated to fix more than one suffix
Strrpos is far better than regex on such a simple string problem.
$str = "some_text_here_13_15";
While(is_numeric(substr($str, strrpos($str, "_")+1))){
$str = substr($str,0 , strrpos($str, "_"));
}
Echo $str;
Strrpos finds the last "_" in str and if it's numeric remove it.
https://3v4l.org/OTdb9
Just to give you an idea of what I mean with regex not being a good solution on this here is the performance.
Regex:
https://3v4l.org/Tu8o2/perf#output
0.027 seconds for 100 runs.
My code with added numeric check:
https://3v4l.org/dkAqA/perf#output
0.003 seconds for 100 runs.
This new code performs even better than before oddly enough, regex is very slow. Trust me on that
You be the judge on what is best.
First you'll want to do a preg_replace() in order to remove all digits by using the regex /\d+/. Then you'll also want to trim any underscores from the right using rtrim(), providing _ as the second parameter.
I've combined the two in the following example:
$string = "some_text_here_1";
echo rtrim(preg_replace('/\d+/', '', $string), '_'); // some_text_here
I've also created an example of this at 3v4l here.
Hope this helps! :)
$reg = '#_\d+$#';
$replace = '';
echo preg_replace($reg, $replace, $string);
This would do
abc_def_ghi_123 > abc_def_ghi
abc_def_1 > abc_def
abc_def_ghi > abc_def_ghi
abd_def_ > abc_def_
abc_123_def > abd_123_def
in case of abd_def_123_345 > abc_def
one could change the line
$reg = '#(?:_\d+)+$#';

Regex rules in an array

Maybe it can not be solved this issue as I want, but maybe you can help me guys.
I have a lot of malformed words in the name of my products.
Some of them has leading ( and trailing ) or maybe one of these, it is same for / and " signs.
What I do is that I am explode the name of the product by spaces, and examines these words.
So I want to replace them to nothing. But, a hard drive could be 40GB ATA 3.5" hard drive. I need to process all the word, but I can not use the same method for 3.5" as for () or // because this 3.5" is valid.
So I only need to replace the quotes, when it is at the start of the string AND at end of the string.
$cases = [
'(testone)',
'(testtwo',
'testthree)',
'/otherone/',
'/othertwo',
'otherthree/',
'"anotherone',
'anothertwo"',
'"anotherthree"',
];
$patterns = [
'/^\(/',
'/\)$/',
'~^/~',
'~/$~',
//Here is what I can not imagine, how to add the rule for `"`
];
$result = preg_replace($patterns, '', $cases);
This is works well, but can it be done in one regex_replace()? If yes, somebody can help me out the pattern(s) for the quotes?
Result for quotes should be this:
'"anotherone', //no quote at end leave the leading
'anothertwo"', //no quote at start leave the trailin
'anotherthree', //there are quotes on start and end so remove them.
You may use another approach: rather than define an array of patterns, use one single alternation based regex:
preg_replace('~^[(/]|[/)]$|^"(.*)"$~s', '$1', $s)
See the regex demo
Details:
^[(/] - a literal ( or / at the start of the string
| - or
[/)]$ - a literal ) or / at the end of the string
| - or
^"(.*)"$ - a " at the start of the string, then any 0+ characters (due to /s option, the . matches a linebreak sequence, too) that are captured into Group 1, and " at the end of the string.
The replacement pattern is $1 that is empty when the first 2 alternatives are matched, and contains Group 1 value if the 3rd alternative is matched.
Note: In case you need to replace until no match is found, use a preg_match with preg_replace together (see demo):
$s = '"/some text/"';
$re = '~^[(/]|[/)]$|^"(.*)"$~s';
$tmp = '';
while (preg_match($re, $s) && $tmp != $s) {
$tmp = $s;
$s = preg_replace($re, '$1', $s);
}
echo $s;
This works
preg_replace([[/(]?(.+)[/)]?|/\"(.+)\"/], '$1', $string)

Remove empty space and plus sign from the beginning of a string

I have a string that begins with an empty space and a + sign :
$s = ' +This is a string[...]';
I can't figure out how to remove the first + sign using PHP. I've tried ltrim, preg_replace with several patterns and with trying to escape the + sign, I've also tried substr and str_replace. None of them is removing the plus sign at the beginning of the string. Either it doesn't replace it or it remplace/remove the totality of the string. Any help will be highly appreciated!
Edit : After further investigation, it seems that it's not really a plus sign, it looks 100% like a + sign but I think it's not. Any ideas for how to decode/convert it?
Edit 2 : There's one white space before the + sign. I'm using get_the_excerpt Wordpress function to get the string.
Edit 3 : After successfully removing the empty space and the + with substr($s, 2);, Here's what I get now :
$s == '#43;This is a string[...]'
Wiki : I had to remove 6 characters, I've tried substr($s, 6); and it's working well now. Thanks for your help guys.
ltrim has second parameter
$s = ltrim($s,'+');
edit:
if it is not working it means that there is sth else at the beginning of that string, eg. white spaces. You can check it by using var_dump($s); which shows you exactly what you have there.
You can use explode like this:
$result = explode('+', $s)[0];
What this function actually does is, it removes the delimeter you specify as a first argument and breaks the string into smaller strings whenever that delimeter is found and places those strings in an array.
It's mostly used with multiple ocurrences of a certain delimeter but it will work in your case too.
For example:
$string = "This,is,a,string";
$results = explode(',', $string);
var_dump($results); //prints ['This', 'is', 'a', 'string' ]
So in your case since the plus sign appears ony once the result is in the zero index of the returned array (that contains only one element, your string obviously)
Here's a couple of different ways I can think of
str_replace
$string = str_replace('+', '', $string);
preg_replace
$string = preg_replace('/^\+/', '', $string);
ltrim
$string = ltrim($string, '+');
substr
$string = substr($string, 1);
try this
<?php
$s = '+This is a string';
echo ltrim($s,'+');
?>
You can use ltrim() or substr().
For example :
$output = ltrim($string, '+');
or you can use
$output = substr($string, 1);
You can remove multiple characters with trim. Perhaps you were not re-assigning the outcome of your trim function.
<?php
$s = ' +This is a string[...]';
$s = ltrim($s, '+ ');
print $s;
Outputs:
This is a string[...]
ltrim in the above example removes all spaces and addition characters from the left hand side of the original string.

Removing all characters and numbers except last variable with dash symbol

Hi I want to remove a characters using preg_replace in php so i have this code here which i want to remove the whole characters, letters and numbers except the last digit(s) which has dash(-) symbol followed by a digits so here's my code.
echo preg_replace('/(.+)(?=-[0-9])|(.+)/','','asdf1245-10');
I expect the result will be
-10
the problem is above is not working very well. I checked the pattern using http://www.regextester.com/ it seems like it works, but on the other side http://www.phpliveregex.com/ doesn't work at all. I don't know why but anyone who can help to to figure it out?
Thanks a lot
Here is a way to go:
echo preg_replace('/^.+?(-[0-9]+)?$/','$1','asdf1245-10');
Output:
-10
and
echo preg_replace('/^.+?(-[0-9]+)?$/','$1','asdf124510');
Output:
<nothing>
My first thinking is to use explode in this case.. make it simple like the following code.
$string = 'asdf1245-10';
$array = explode('-', $string);
end($array);
$key = key($array);
$result = '-' . $array[$key];
$result => '-10';
An other way:
$result = preg_match('~\A.*\K-\d+\z~', $str, $m) ? $m[0] : '';
pattern details:
\A # start of the string anchor
.* # zero or more characters
\K # discard all on the left from match result
-\d+ # the dash and the digits
\z # end of the string anchor
echo preg_replace('/(\w+)(-\w+)/','$2', 'asdf1245-10');

php remove everything in the string, keep the last digits

I have values like below:
$var1 = car-123-244343
$var2 = boat-2-1
$var3 = plane-311-23
I need to remove everything and keep the last digit/ditgits after the second hyphen
Expecting values:
244343
1
23
This is what I've got
$stripped = preg_replace('^[a-z]+[-]$', '', 'car-123-244343');
I got a big red error No ending delimiter '^' found
Without regex:
$var1 = substr($var1, strrpos($var1, '-') + 1);
What this does is the same as:
$pos = strrpos($var1, '-') + 1 takes the last postion of '-' and adds 1 for starting at the next character
substr($var, $pos) takes the $var and returns the substring starting in $pos.
I think is less expensive than using regex.
Edit:
As pointed below by konforce, if you are not sure which all the strings have that format, you have to verify it.
this function will work:
function foo($value)
{
$split = explode('-', $value);
return $split[count($split)-1];
}
Here is a fun version with explode:
list($vehicle, $no1, $no2) = explode('-', $data);
First, that error means your regex needs to be enclosed in delimiters (below I use the classic /).
Second, I would rewrite your regex to this:
$stripped = preg_replace('/.+?(\d+)$/', '$1', 'car-123-244343');
If you can operate on the assumption that what comes after the last - is always a number, the other solutions also work.
With regex:
$endnumber = preg_replace('/.*[^0-9]/', '', $input);
Remove everything up till, and including, the last non-digit.

Categories