I'm trying to replace only the first character of a string, but it isn't working, it replaces all the "0" on the string, here's my code:
$mes2 = str_replace('0', '', $mes[0]);
I want to replace the first character only if its a 0, example:
07 becomes 7
I don't want to replace all the time, example:
11 becomes 1, i don't want it.
I also tried this way, but it didn't work the way i want, because it's replacing also the second character if it's 0, like 10 becomes 1.
$mes2 = preg_replace('/0/', '', $mes, 1);
The string function substr will pull the first character from the passed string and if the first character matches with your replace character it will replace else it will show the original only.
The str_replace() is a built-in function in PHP and is used to replace all the occurrences of the search string or array of search strings by replacement string or array of replacement strings in the given string or array respectively.
The substr_replace() function replaces a part of a string with another string. Note: If the start parameter is a negative number and length is less than or equal to start, length becomes 0. Note: This function is binary-safe.
OK, based on refinements to your question, what you probably want is ltrim
.
$out = ltrim($in, "0");
This will strip all leading zeroes from $in
. It won't remove zeroes from anywhere else, and it won't remove anything other than zeroes. Be careful; if you give it "000" you'll get back "" instead of "0".
You could use typecasting instead, as long as $in
is always a number (or you want it to result in 0 if it isn't):
$out = (int) $in;
...etc.
Now, in the unlikely event that you only want to replace the first 0, so for example "007" becomes "07", then your latest attempt mentioned in your question is almost there. You just need to add a "caret" character to make sure it only matches the start of the string:
$out = preg_replace('/^0/', '', $in);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With