I have a number string in Persian numbers for example
۱۱۲۵۱۲۰۱۲۴
which is 1125120124 in English numerical. I want to convert this string to number format separated by commas after every thousand for example
۱,۱۲۵,۱۲۰,۱۲۴
like when I do
number_format(1125120124); // it returns as 1,125,120,124
and
number_format(112512012); // it returns as 112,512,012
So actualy I want similar results as of number_format method. I just started regular expressions. Tried with very basic patterns but still no where near. Tried preg_split to split string and concatenate it again with commas but does not seem to be right approach. I have a function where I pass a number that returns me that number in Persian characters. Sharing that too
function trans($num)
{
$persian_num_array = [
'0'=>'۰',
'1'=>'۱',
'2'=>'۲',
'3'=>'۳',
'4'=>'۴',
'5'=>'۵',
'6'=>'۶',
'7'=>'۷',
'8'=>'۸',
'9'=>'۹',
];
$translated_num = '';
$temp_array=[];
while ($num > 0) {
array_push($temp_array,$num % 10);
$num = intval($num / 10);
}
foreach($temp_array as $val){
$translated_num.= $persian_num_array[array_pop($temp_array)];
}
echo $translated_num;
}
As converting to Persian is a just character replacing, you can format number using built-in number_format() function and then replace numbers without replacing commas. Here is an example:
function trans($num)
{
$persian_num_array = [
'0'=>'۰',
'1'=>'۱',
'2'=>'۲',
'3'=>'۳',
'4'=>'۴',
'5'=>'۵',
'6'=>'۶',
'7'=>'۷',
'8'=>'۸',
'9'=>'۹',
];
$num = (float) $num;
return strtr(number_format($num), $persian_num_array);
}
echo trans(1125120124); // returns ۱,۱۲۵,۱۲۰,۱۲۴
PHP's Intl extension includes a NumberFormatter class that can format your number for a given locale.
Example:
$number = "1125120124";
$formatter = NumberFormatter::create("fa_IR", NumberFormatter::DEFAULT_STYLE);
echo $formatter->format($number);
Output:
۱٬۱۲۵٬۱۲۰٬۱۲۴
To force a comma to be used, it has a setSymbol() method.
Example:
$number = "1125120124";
$formatter = NumberFormatter::create("fa_IR", NumberFormatter::DEFAULT_STYLE);
$formatter->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, ",");
echo $formatter->format($number);
Output:
۱,۱۲۵,۱۲۰,۱۲۴
Or if your input was in Persian, first use a Transliterator on it.
Example:
$input = "۱۱۲۵۱۲۰۱۲۴";
$transliterator = Transliterator::create("fa-fa_Latn/BGN");
$number = $transliterator->transliterate($input);
echo $number, "\n";
$formatter = NumberFormatter::create("fa_IR", NumberFormatter::DEFAULT_STYLE);
$formatter->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, ",");
echo $formatter->format($number);
Output:
1125120124
۱,۱۲۵,۱۲۰,۱۲۴
Related
I have rand function like;
$mynumbers = rand(1111,9999);
echo $mynumbers;
Example output is
3582
and I have another strings
$mystring = "Ja9Js78I4PhXiF464R6s7ov8IUF"; (Have 1 number, must be turn 1 (only 8 have))
$mystring2 = "Ja3Js73I4P1X5iF564R8s2ov8IUF"; (Have 4 numbers, must be turn 4 (have all of them))
And i want to know this with function ;
$mystring is have, how many numbers ? inside $mynumbers and how many time ? passed when this process ? How can i do it ?
per your last comment. Treat the integer as a string (PHP is good at that). And iterate by character.
<?php
$foo = '1234';
$mystring = [];
$mystring[] = 'A1B2KLDLDF3'; //3
$mystring[] = 'XXXX4XXXX'; //1
foreach ($mystring as $key => $string) {
echo "mystring {$key}: ";
$c = 0;
foreach(str_split($foo) as $char) {
$c = $c + substr_count($string, $char);
}
echo $c . '<br/>';
}
mystring 0: 3
mystring 1: 1
As this is PHP you also need to be aware of mb_ multibyte functions. See: http://php.net/manual/en/function.mb-substr-count.php
Update:
Sounds like you should clean up the string you are checking then if you want to discard all duplicates... Could then of course use a substr or other method perhaps more performant than substr_count.
$mystring = 'A111111B2KLDLDF333'; //3
$mystring = implode('',array_unique(str_split($mystring)));
//gives 'A1B2KLDF3'
I have a string like this:
9.018E-14
Now I want to convert to this to the normal decimal numbers.
MyGeekPal has a nice article on it.
Code:
<?php
$total_time = 2.8848648071289E-5;
echo exp2dec($total_time);
function exp2dec($number) {
preg_match('/(.*)E-(.*)/', str_replace(".", "", $number), $matches);
$num = "0.";
while ($matches[2] > 0) {
$num .= "0";
$matches[2]--;
}
return $num . $matches[1];
}
?>
If your input is a float
If you have $number = 0.00023459 then printing this value in PHP will probably result in this exponential format. It doesn't mean the variable is stored that way; it's just an output artefact.
Use printf to work around this and gain control over your numeric output.
If your input is a string
Why the complexity?
$matches = Array();
if (preg_match('/(.*)E-(.*)/', $number, $matches)) {
$number = $matches[1] * pow(10, -1*$matches[2]);
}
Though you can tighten up the regex a bit:
$matches = Array();
if (preg_match('/(\d+(?:\.\d+)?)E(-?\d+)/i', $number, $matches)) {
$number = (float)$matches[1] * pow(10, (int)$matches[2]);
}
Live demo
EDIT: Here is some PHP magic:
$stringval = "12e-3";
$numericval = 0 + $stringval;
From the PHP docs:
If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.
If you need a more flexible format (e.g. extract four numbers from the same string), use sscanf like this:
$stringval = "12e-3";
$numericval = sscanf($stringval, "%f")[0];
echo $numericval;
I have an array that contains values of 1 or 0 representing true or false values. e.g.
array(1,0,0,1,0,1,1,1,1);
I want to compress/encode this array into the shortest string possible so that it can be stored within a space constrained place such as a cookie. It also need to be able to be decoded again later. How do I go about this?
ps. I am working in PHP
Here is my proposal:
$a = array(1,0,0,1,0,1,1,1,1,1,0,0,1,0,1,1,1,1,1,0,0,1,0,1,1,1,1);
$compressed = base64_encode(implode('', array_map(function($i) {
return chr(bindec(implode('', $i)));
}, array_chunk($a, 8))));
var_dump($compressed); // string(8) "l8vlBw=="
So you get each 8 characters (which in fact is a binary 0..255), convert them to an integer, represent as an ASCII character, implode it to a string and convert to base64 to be able to save it as a string.
UPD:
the opposite is pretty straightforward:
$original = str_split(implode('', array_map(function($i) {
return decbin(ord($i));
}, str_split(base64_decode($compressed)))));
How exactly I wrote it (just in case anyone interesting how to write such unreadable and barely maintainable code):
I've written the $original = $compressed; and started reversing the right part of this expression step by step:
Decoded from base64 to a binary string
Split it to an array
Converted every character to its ASCII code
Converted decimal ASCII code to a binary
Joined all the binary numbers into a single one
Split the long binary string to an array
Dont use serialize. Just make a string of it:
<?php
$string = implode( '', $array );
?>
You are left with an string like this:
100101111
If you want to have an array again, just access it like an array:
$string = '100101111';
echo $string[1]; // returns "0"
?>
Of course you could also make it a decimal and just store the number. That's even shorter then the "raw" bits.
<?php
$dec = bindec( $string );
?>
How about pack and unpack
$arr = array(1,1,1,1,0,0,1,1,0,1,0,0,1,1,0,0,1,1,1,1);
$str = implode($arr);
$res = pack("h*", $str);
var_dump($res);
$rev = unpack("h*", $res);
var_dump($rev);
output:
string(10) # Not visible here
array(1) {
[1]=>
string(20) "11110011010011001111"
}
Here is my solution based on zerkms answer, this deals with the loss of leading 0's when converting decimals back into binary.
function compressBitArray(array $bitArray){
$byteChunks = array_chunk($bitArray, 8);
$asciiString = implode('', array_map(function($i) {
return chr(bindec(implode('', $i)));
},$byteChunks));
$encoded = base64_encode($asciiString).'#'.count($bitArray);
return $encoded;
}
//decode
function decompressBitArray($compressedString){
//extract origional length of the string
$parts = explode('#',$compressedString);
$origLength = $parts[1];
$asciiChars = str_split(base64_decode($parts[0]));
$bitStrings = array_map(function($i) {
return decbin(ord($i));
}, $asciiChars);
//pad lost leading 0's
for($i = 0; $i < count($bitStrings); $i++){
if($i == count($bitStrings)-1){
$toPad = strlen($bitStrings[$i]) + ($origLength - strlen(implode('', $bitStrings)));
$bitStrings[$i] = str_pad($bitStrings[$i], $toPad, '0', STR_PAD_LEFT);
}else{
if(strlen($bitStrings[$i]) < 8){
$bitStrings[$i] = str_pad($bitStrings[$i], 8, '0', STR_PAD_LEFT);
}
}
}
$bitArray = str_split(implode('', $bitStrings));
return $bitArray;
}
I have a whole bunch of percentages stored as XX% (e.g. 12%, 50%, etc..) I need to remove the percentage sign and then multiply the percent against another variable thats just a number (e.g. 1000, 12000) and then output the result. Is there a simple way to strip the percentage sign and then calculate the output with PHP? Or should I consider some sort of JS solution?
You could use rtrim():
$value = ((int) rtrim('12%', '%')) * 1000';
Edit
You don't strictly need to call rtrim() , as it casts to an int ok with the percentage sign. It is probably cleaner to strip it though.
var_dump (12 === (int) '12%');
//output: bool(true)
You can make use of preg_replace_callback as:
$input = '12%, 50%';
$input = preg_replace_callback("|(\d+)%|","replace_precent",$input);
echo $input; // 12000, 50000
function replace_precent($matches) {
return $matches[1] * 1000;
}
Try this:
$number = str_replace('%', '', '100%');
$result = intval($number) * 5000; // or whatever number
echo $result;
If you use trim() or str_replace() in PHP you can remove the percent sign. Then, you should be able to multiply the resulting number (php is weakly typed after all).
<?php
$number = str_replace("%", "", $percentString);
$newNumber = ((int) $number) * 1000;
echo $newNumber;
?>
You can use str_replace. You can also pass an array of subjects into str_replace to have them all replaced.
<?php
$number = str_replace("%", "", $percentage);
$result = $number * $other_var;
print $result;
?>
<?php
$input=array('15%','50%','10.99%','21.5%');
$multiplier=1000;
foreach($input as $n){
$z=floatval($n)*$multiplier;
print("$z<br>");
}
?>
Just looked at function
str_pad($input, $pad_length, $pad_str, [STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH])
which helps to pad some string on left, right or on both sides of a given input.
Is there any php function which I can use to insert a string inside an input string?
for example ..
$input = "abcdef";
$pad_str = "#";
so if I give insert index 3, it inserts "#" after first 3 left most characters and $input becomes "abc#def".
thanks
You're looking for a string insert, not a padding.
Padding makes a string a set length, if it's not already at that length, so if you were to give a pad length 3 to "abcdef", well it's already at 3, so nothing should happen.
Try:
$newstring = substr_replace($orig_string, $insert_string, $position, 0);
PHP manual on substr_replace
you need:
substr($input, 0, 3).$pad_str.substr($input, 3)
Bah, I misread the question. You want a single insert, not insert every X characters. Sorry.
I'll leave it here so it's not wasted.
You can use regular expressions and some calculation to get your desired result (you probably could make it with pure regexp, but that would be more complex and less readable)
vinko#mithril:~$ more re.php
<?php
$test1 = "123123123";
$test2 = "12312";
echo puteveryXcharacters($a,"#",3);
echo "\n";
echo puteveryXcharacters($b,"#",3);
echo "\n";
echo puteveryXcharacters($b,"$",3);
echo "\n";
function puteveryXcharacters($str,$wha,$cnt) {
$strip = false;
if (strlen($str) % $cnt == 0) {
$strip = true;
}
$tmp = preg_replace('/(.{'.$cnt.'})/',"$1$wha", $str);
if ($strip) {
$tmp = substr($tmp,0,-1);
}
return $tmp;
}
?>
vinko#mithril:~$ php re.php
123#123#123
123#12
123$12