Decimal lost while extracting digits from a string in PHP [duplicate] - php

This question already has answers here:
PHP and preg_match Regex to pull number with decimal out of string
(4 answers)
Closed 4 years ago.
I am trying to extract digits and decimal point from a string but the decimal point is lost when I am using following regular expression:
<?php
$str = "$40.0000";
echo $str;
echo "<br />";
$pattern = "/\D+/";
$str = preg_replace($pattern, '', $str);
echo $str;
?>
Output:
$40.0000
400000
I want to retain dot also. How to include dot in my regex?

<?php
$str = '$40000.00';
echo preg_replace('/[^\d.]/','',$str);
Several good answers here, too: How do I convert output of number_format back to numbers in PHP?

There are two appropriate functions for this purpose. The first, round(), rounds a value to a specified number of decimal places. The function’s first argument is the number to be rounded. This can be either a number or a variable with a number value. The second argument is optional; it represents the number of decimal places to round to. For example:
round (4.30); // 4
round (4.289, 2); // 4.29
$num = 236.26985;
round ($num); // 236
The other function you can use in this situation is number_format(). It works like round() in that it takes a number (or a variable with a numeric value) and an optional decimal specifier. This function has the added benefit of formatting the number with commas, the way it would commonly be written:
number_format (428.4959, 2); // 428.50
number_format (428, 2); // 428.00
number_format (123456789); // 123,456,789

Related

Exploding a number and separate it by a space [duplicate]

This question already has answers here:
Insert string at specified position
(11 answers)
separate string in two by given position
(8 answers)
Closed 4 years ago.
I want to explode a string or an integer and separate it by a space.
E.g., I have this int 12345678, and I want its numbers to become like 123 45678. I want the first three numbers separated. Can someone give me a clue or hint in how to achieve this, like what function to use in PHP? I think using an explode will not work here because the explode function needs a separator.
You can use substr_replace() - Replace text within a portion of a string.
echo substr_replace(1234567, " ", 3, 0); // 123 4567
https://3v4l.org/9CFlX
You could use substr() :
$str = "12345678" ;
echo substr($str,0,3)." ".substr($str, 3); // "123 45678"
Also works with an integer :
$int = 12345678 ;
echo substr($int,0,3)." ".substr($int, 3); // "123 45678"
This problem will solve by using substr().
The substr() function returns a part of a string.
Syntax: substr(string,start,length)
Example:
$value = "12345678";
echo substr($value,0,3)." ".substr($value, 3);
Output: 123 45678
You may get better understand from here.

Big numbers regex

$value = preg_replace("/[^0-9]+/", '', $value);
How could I edit this regex to get rid of everything after the decimal point? There may or may not be a decimal point.
Currently "100.1" becomes 1001 but it should be 100.
Complete function:
function intfix($value)
{
$value = preg_replace("/[^0-9]+/", '', $value);
$value = trim($value);
return $value + 0;
}
It is used to format user input for numbers as well as servers output to format numbers for the DB. The functions deals with very large numbers, so I can't use intval or similar. Any extra comments to improve this function are welcome.
You could just change the regex to /[^0-9].*/s.
.* matches zero or more characters, so the first character that is not a digit, and the digits that immediately follow, would be deleted.
You need to have a pattern that starts the search with a decimal place. At the moment you're only deleting the . not the numbers after it... So you could do '/\.[\d]+/'
$text = "1201.21 12 .12 12.21";
$text = preg_replace('/\.[\d]+/', '' ,$text);
The above code would result in $text = "1201 12 12"
Why not $value = round($value, 0);? This can handle large values and is meant to get rid of the following decimals mathematically (I'd rather work with numbers as numbers not as strings). You can pass PHP_ROUND_HALF_DOWN as a third parameter if you want to just get rid of the decimals 10.7 -> 10. Or floor($value); could work too.

What does %S mean in PHP, HTML or XML? [duplicate]

This question already has answers here:
What does the syntax '%s' and '%d' mean as shorthand for calling a variable?
(3 answers)
Closed 11 months ago.
I'm looking at Webmonkey's PHP and MySql Tutorial, Lesson 2. I think it's a php literal. What does %s mean? It's inside the print_f() function in the while loops in at least the first couple of code blocks.
printf("<tr><td>%s %s</td><td>%s</td></tr>n", ...
with printf or sprintf characters preceded by the % sign are placeholders (or tokens). They will be replaced by a variable passed as an argument.
Example:
$str1 = 'best';
$str2 = 'world';
$say = sprintf('Tivie is the %s in the %s!', $str1, $str2);
echo $say;
This will output:
Tivie is the best in the world!
Note: There are more placeholders (%s for string, %d for dec number, etc...)
Order:
The order in which you pass the arguments counts. If you switch $str1 with $str2 as
$say = sprintf('Tivie is the %s in the %s!', $str2, $str1);
it will print
"Tivie is the world in the best!"
You can, however, change the reading order of arguments like this:
$say = sprintf('Tivie is the %2$s in the %1$s!', $str2, $str1);
which will print the sentence correctly.
Also, keep in mind that PHP is a dynamic language and does not require (or support) explicit type definition. That means it juggles variable types as needed. In sprint it means that if you pass a "string" as argument for a number placeholder (%d), that string will be converted to a number (int, float...) which can have strange results. Here's an example:
$onevar = 2;
$anothervar = 'pocket';
$say = sprintf('I have %d chocolate(s) in my %d.', $onevar, $anothervar);
echo $say;
this will print
I have 2 chocolate(s) in my 0.
More reading at PHPdocs
In printf, %s is a placeholder for data that will be inserted into the string. The extra arguments to printf are the values to be inserted. They get associated with the placeholders positionally: the first placeholder gets the first value, the second the second value, and so on.
%s is a type specifier which will be replaced to valuable's value (string) in case of %s.
Besides %s you can use other specifiers, most popular are below:
d - the argument is treated as an integer, and presented as a (signed) decimal number.
f - the argument is treated as a float, and presented as a floating-point number (locale
aware).
s - the argument is treated as and presented as a string.
$num = 5;
$location = 'tree';
$format = 'There are %d monkeys in the %s';
echo sprintf($format, $num, $location);
Will output: "There are 5 monkeys in the tree."
The printf() or sprintf() function writes a formatted string to a variable.
Here is the Syntax:
sprintf(format,arg1,arg2,arg++)
format:
%% - Returns a percent sign
%b - Binary number
%c - The character according to the ASCII value
%d - Signed decimal number (negative, zero or positive)
%e - Scientific notation using a lowercase (e.g. 1.2e+2)
%E - Scientific notation using a uppercase (e.g. 1.2E+2)
%u - Unsigned decimal number (equal to or greater than zero)
%f - Floating-point number (local settings aware)
%F - Floating-point number (not local settings aware)
%g - shorter of %e and %f
%G - shorter of %E and %f
%o - Octal number
%s - String
%x - Hexadecimal number (lowercase letters)
%X - Hexadecimal number (uppercase letters)
arg1:
The argument to be inserted at the first %-sign in the format
string..(Required.)
arg2:
The argument to be inserted at the second %-sign in the format
string. (Optional)
arg++:
The argument to be inserted at the third, fourth, etc. %-sign in
the format string (Optional)
Example 1:
$number = 9;
$str = "New York";
$txt = sprintf("There are approximately %u million people in %s.",$number,$str);
echo $txt;
This will output:
There are approximately 9 million people in New York.
The arg1, arg2, arg++ parameters will be inserted at percent (%) signs in the main string. This function works "step-by-step". At the first % sign, arg1 is inserted, at the second % sign, arg2 is inserted, etc.
Note: If there are more % signs than arguments, you must use
placeholders. A placeholder is inserted after the % sign, and consists
of the argument- number and "\$". Let see another Example:
Example 2
$number = 123;
$txt = sprintf("With 2 decimals: %1\$.2f
<br>With no decimals: %1\$u",$number);
echo $txt;
This will output:
With 2 decimals: 123.00
With no decimals: 123
Another important tip to remember is that:
With printf() and sprintf() functions, escape character is not
backslash '\' but rather '%'. Ie. to print '%' character you need to
escape it with itself:
printf('%%%s%%', 'Nigeria Naira');
This will output:
%Nigeria Naira%
Feel free to explore the official PHP Documentation

Set string to a specified length in PHP [duplicate]

This question already has answers here:
Zero-pad digits in string
(5 answers)
Closed 11 months ago.
I need to have a string that has a specified length and replace the excess characters with a letter.
e.g.
My original string is : "JOHNDOESMITH". The length should be up to 25 characters only.
I need my string to become "XXXXXXXXXXXXXJOHNDOESMITH" (13 X's and 12 chars from the original string).
Anybody please tell me how to achieve this? Is there a string function for this? I've been racking my brains out for quite some time now and I still can't find a solution.
You could use str_pad() to do it...
echo str_pad($str, 25, 'X', STR_PAD_LEFT);
CodePad.
You could use str_repeat() to do it...
echo str_repeat('X', max(0, 25 - strlen($str))) . $str;
CodePad.
The length should be up to 25 characters only.
You can always run substr($str, 0, 25) to truncate your string to the first 25 characters.
We can use printf() or sprintf() function.
$format= "%'X25s";
printf($format, "JOHNDOESMITH"); // Prints a formatted string
$output = sprintf($format, "JOHNDOESMITH"); // Returns a formatted string
Use the str_pad function:
$a="JOHNDOESMITH";
$b=str_pad($a,25,'X',STR_PAD_LEFT);
print_r($b);

php preg_match_all results from (numerical) STRING to DECIMAL - type

I have script that identifies with preg_match_all some numbers from a given file and in a given format '#(\d\,\d\d\d\d)#' (decimal, with 4 decimals). With them, later, I need to do some math operations to find out the sum, average etc.
With print_r I can see all matches from the array and it is ok (4,3456, 4,9098, etc.). I verify the type of variables and gettype() returned string
Unfortunately I cannot do math operations with them because when I use the variables in a math expression the result is always rounded regardless of what came afer the comma.
For example:
4,3456 + 4,9098 + 4,3456 = 12, or 12,0000 -- if I use number_format.
I used . instead of , in the numbers, I formatted the results with number_format, but have had no success. It seems I am missing something.
Thanks for help!
The error happens even before the number_format call -- PHP considers . as the decimal separator, not ,. you need to str_replace all your array elements:
$values_array = str_replace(",", ".", $values_array)
PHP uses the . character as decimal separator, so you have to replace the , by a . in your matched numbers before converting them to numbers:
$number = floatval(strtr("1,234", ",", "."));
// 1.234
Example:
<?php
$numbers = array("1,234", "5,67");
$numbers = str_replace(",", ".", $numbers);
echo number_format($numbers[0] + $numbers[1], 4, ',', ' ');
Try it here: http://codepad.org/LeeTiKPF

Categories