I am trying to find a way to remove a decimal point from a number.
E.g.
1.11 would equal 111
9.99 would equal 999
1.1111 would equal 11111
Can't seem to find the function I need to do this. I have been googling to find this function but no luck.
I have tried these functions but it is not what I am looking for:
floor(99.99) = 99
round(99.99) = 100
number_format(99.99) = 100
This should work for you:
<?php
$str = "9.99";
echo $str = str_replace(".", "", $str);
?>
Output:
999
We can use explode:
$num = 99.999;
$final = '';
$segments = explode($num, '.');
foreach ($segments as $segment){
$final .= $segment;
}
echo $final;
Checkout this demo: http://codepad.org/DMiFNYfB
Generalizing the solution for any local settings variations we can use preg_split as follows:
$num = 99.999;
$final = '';
$pat = "/[^a-zA-Z0-9]/";
$segments = preg_split($pat, $num);
foreach ($segments as $segment){
$final .= $segment;
}
echo $final;
Also, there are another solution using for loop:
<?php
$num = 99.999;
$num = "$num"; //casting number to be string
$final = '';
for ($i =0; $i < strlen($num); $i++){
if ($num[$i] == '.') continue;
$final .= $num[$i];
}
echo $final;
If you want to simply remove the decimal, you can just replace it.
str_replace('.', '', $string);
You could just treat it as a string and remove the . character:
$num = str_replace ('.', '', $num);
Try:
$num = 1.11; // number 1.11
$num_to_str = strval($num); // convert number to string "1.11"
$no_decimals = str_replace(".", "", $num_to_str); // remove decimal point "111"
$str_to_num = intval($no_decimals); // convert back to number 111
All in one line would be something like:
$num_without_decimals = intval(str_replace(".", "", strval(1.11)));
Related
I have a string with this value:
$myValue = "1.099,90";
And I want to replace commas with dots and vice versa. Just like this:
$myNewValue = "1,099.90";
I know that there must be other better ways of doing this, but all I can get is:
$myNewValue = str_replace(",","|",$myValue);
$myNewValue = str_replace(".",",",$myValue);
$myNewValue = str_replace("|",".",$myValue);
This way looks weird and has a bad smell! Is there a cleaner way?
strtr() doesn't replace replacements, so you can avoid the temporary piping.
Code: (Demo)
$myValue = "7.891.099,90";
echo strtr($myValue, ".,", ",.");
// or
// echo strtr($myValue, ["." => ",", "," => "."]);
Output:
7,891,099.90
Resource: http://php.net/manual/en/function.strtr.php
This will get the job done, but you could definitely use preg_replace to come up with a different method as well.
<?php
$myValue = '1.099,90';
$parts = explode(".", $myValue); // break up the (.)periods
$num = count($parts); // number of parts
for($loop = 0; $loop < $num; $loop++){ // cycle through each part
if(strpos($parts[$loop], ",") !== false){ // if this includes (,)comma - swap it
$parts[$loop] = str_replace(",", ".", $parts[$loop]);
}
if($loop !== ($num - 1)){ // if this is not the last loop iteration..add comma after (replace period)
$myNewValue .= $parts[$loop] . ",";
} else {
$myNewValue .= $parts[$loop]; // last loop iteration, no comma at end
}
}
echo $myNewValue;
You can also use the str_replace w/ extra | symbol (or anything)...
<?php
$myValue = '1.099,90';
$replace = array(",", ".", "|");
$with = array("|", ",", ".");
$myNewValue = str_replace($replace, $with, $myValue);
echo $myNewValue;
?>
In my DB i have items names that can be input by users either in the form of Apple MM1 or Banana B-234 or Carl Mm345 (I can't really control too much what users input)
I'd like to be able to convert Carl Mm345 and convert it in Carl MM-345 by using PHP: basically adding a dash or hyphen and uppercase all the letter before dash
function convert_input($string) {
$arr = explode(' ', $string);
if (count($arr) == 1) {
$first = '';
$second = strtoupper($string);
} else {
$first = $arr[0].' ';
$second = strtoupper($arr[1]);
}
$second = str_replace('-', '', $second);
$p = strcspn($second, '0123456789');
$letters = substr($second, 0, $p);
$numbers = substr($second, $p);
$glue = $letters && $numbers ? '-' : '';
return $first.$letters.$glue.$numbers;
}
echo convert_input('mm234');
echo convert_input('Carl Mm345');
echo convert_input('adsf mmmm');
echo convert_input('adsf');
echo convert_input('adsfdsf 123');
echo convert_input('Banana B-234');
I'm not sure exactly what you want, and it's probably more efficient to create a regex expression, but this PHP function seems to accomplish what you want. I generalized the rules you gave in the question (also note that strtoupper makes no difference if the number is upper-cased)
function convert($string) {
$tmp = explode(' ', $string);
$t = '';
$var = str_split($tmp[1]);
for ($i = 0; $i < count($var); $i++) {
if (is_numeric($var[$i])) {
$t .= '-';
}
$t .= strtoupper($var[$i]);
}
return implode('', array($tmp[0])) . $t;
}
$str = 'ABC300';
How I can get values like
$alphabets = "ABC";
$numbers = 333;
I have a idea , first remove numbers from the string and save in a variable. then remove alphabets from the $str variable and save. try the code
$str = 'ABC300';
$alf= trim(str_replace(range(0,9),'',$str));//removes number from the string
$number = preg_replace('/[A-Za-z]+/', '', $str);// removes alphabets from the string
echo $alf,$number;// your expected output
Try something like this (it's not that fast)...
$string = "ABCDE3883475";
$numbers = "";
$alphabets = "";
$strlen = strlen($string);
for($i = 0; $i <= $strlen; $i++) {
$char = substr($string, $i, 1);
if(is_numeric($char)) {
$numbers .= $char;
} else {
$alphabets .= $char;
}
}
Then all numbers should be in $numbers and all alphabetical characters should be in $alphabets ;)
https://3v4l.org/Xh4FR
A way to do that is to find all digits and use the array to replace original string with the digits inside.
For example
function extractDigits($string){
preg_match_all('/([\d]+)/', $string, $match);
return $match[0];
}
$str = 'abcd1234ab12';
$digitsArray = extractDigits($str);
$allAlphas = str_replace($digitsArray,'',$str);
$allDigits = '';
foreach($digitsArray as $digit){
$allDigits .= $digit;
}
I have a comma delimited string and want the first 100 entries (not including the 100th comma) as a single string.
So for example if I had the string
a,b,c,d,e,f,g
And the problem was get the first 3 entries, the desired result string would be
a,b,c
Using explode/implode:
$str = 'a,b,c,d,e,f,g';
$temp1 = explode(',',$str);
$temp2 = array_slice($temp1, 0, 3);
$new_str = implode(',', $temp2);
Using regex:
$new_str = preg_replace('/^((?:[^,]+,){2}[^,]+).*$/','\1',$str);
try php's explode() function.
$string_array = explode(",",$string);
Loop through the array to get the values you want:
for($i = 0; $i < sizeof($string_array); $i++)
{
echo $string_array[$i];//display values
}
You can do so by finding the 100th delimiter:
$delimiter = ',';
$count = 100;
$offset = 0;
while((FALSE !== ($r = strpos($subject, $delimiter, $offset))) && $count--)
{
$offset = $r + !!$count;
}
echo substr($subject, 0, $offset), "\n";
or similarly tokenize it:
$delimiter = ',';
$count = 100;
$len = 0;
$tok = strtok($subject, $delimiter);
while($tok !== FALSE && $count--)
{
$len += strlen($tok) + !!$count;
$tok = strtok($delimiter);
}
echo substr($subject, 0, $len), "\n";
One way is to split the string after a comma and put the first 100 indexes together (comma-separated).
Before this you have to check if count(array) is greater or smaller than 100.
I have a string like this:
$string = "1,4|2,64|3,0|4,18|";
Which is the easiest way to access a number after a comma?
For example, if I have:
$whichOne = 2;
If whichOne is equal to 2, then I want to put 64 in a string, and add a number to it, and then put it back again where it belongs (next to 2,)
Hope you understand!
genesis'es answer with modification
$search_for = 2;
$pairs = explode("|", $string);
foreach ($pairs as $index=>$pair)
{
$numbers = explode(',',$pair);
if ($numbers[0] == $search_for){
//do whatever you want here
//for example:
$numbers[1] += 100; // 100 + 64 = 164
$pairs[index] = implode(',',$numbers); //push them back
break;
}
}
$new_string = implode('|',$pairs);
$numbers = explode("|", $string);
foreach ($numbers as $number)
{
$int[] = intval($number);
}
print_r($int);
$string = "1,4|2,64|3,0|4,18|";
$coordinates = explode('|', $string);
foreach ($coordinates as $v) {
if ($v) {
$ex = explode(',', $v);
$values[$ex[0]] = $ex[1];
}
}
To find the value of say, 2, you can use $whichOne = $values[2];, which is 64
I think it is much better to use the foreach like everyone else has suggested, but you could do it like the below:
$string = "1,4|2,64|3,0|4,18|";
$whichOne = "2";
echo "Starting String: $string <br>";
$pos = strpos($string, $whichOne);
//Accomodates for the number 2 and the comma
$valuepos = substr($string, $pos + 2);
$tempstring = explode("|", $valuepos);
$value = $tempstring[0]; //This will ow be 64
$newValue = $value + 18;
//Ensures you only replace the index of 2, not any other values of 64
$replaceValue = "|".$whichOne.",".$value;
$newValue = "|".$whichOne.",".$newValue;
$string = str_replace($replaceValue, $newValue, $string);
echo "Ending String: $string";
This results in:
Starting String: 1,4|2,64|3,0|4,18|
Ending String: 1,4|2,82|3,0|4,18|
You could run into issues if there is more than one index of 2... this will only work with the first instance of 2.
Hope this helps!
I know this question is already answered, but I did one-line solution (and maybe it's faster, too):
$string = "1,4|2,64|3,0|4,18|";
$whichOne = 2;
$increment = 100;
echo preg_replace("/({$whichOne},)(\d+)/e", "'\\1'.(\\2+$increment)", $string);
Example run in a console:
noice-macbook:~/temp% php 6642400.php
1,4|2,164|3,0|4,18|
See http://us.php.net/manual/en/function.preg-replace.php