PHP Getting the SUM from two values from a complicated string - php

im kinda new to programming so im sorry if this is a simple question.
I got the following two strings.
<Programvalue>52,45 €<Januari>'
<Programvalue>21,18 €<February>'
I want to get the two values and get the sum of them.
I tried the following
$str1 = "<Programvalue>52,45 €<Januari>";
$str2 = "<Programvalue>21,18 €<February>";
$st1 = explode('>',$str1,0);
$st2 = explode('>',$str2,0);
$s1 = str_replace(" €","",$st1);
$s2 = str_replace(" €","",$st2);
$sum1 = implode( "", $s1 );
$sum2 = implode( "", $s2 );
$sum = $sum1 + $sum2;
echo $sum;
But the output keeps being 0
What do I have to do to get the output 73.63 ?
Thanks for all the help and I'm sorry if this question is really stupid. tbh i kinda feel stupid for not finding a solution myself :(

Simply put:
$str1 = "<Programvalue>52,45 €<Januari>";
$str2 = "<Programvalue>21,18 €<February>";
$st1 = str_replace(array('€', ','), array('', '.'), strip_tags($str1));
$st2 = str_replace(array('€', ','), array('', '.'), strip_tags($str2));
$sum = $st1 + $st2;

Related

Separate string with explode php

I am using explode in PHP, because I need to separate a string. of this type:
$Data = '10 x 4';
I need to separate the numbers because then I do a math operation on them . The code I have works well when they are integers. If I have a string of this type 10 x 2.5 it does not take into account the decimal part that would be the , 5. How can I do to make me take this part into account too?
$data = '10 x 2,5';
$array = explode("x", $data);
$total = $array[0]*$array[1];
Here are two approaches you could take. If you can change the comma separator to a period/full stop:
$data = '10 x 2.5';
$floats = array_map('floatval', explode(' x ', $data));
echo $floats[0] * $floats[1];
Demo: https://3v4l.org/hFMEt
or you could use a regex which also will confirm you have the right data format.
echo preg_replace_callback('/(\d+(?:[.,]\d+)?)\h*x\h*(\d+(?:[.,]\d+)?)/', function($match) {
return str_replace(',' , '.', $match[1]) * str_replace(',' , '.', $match[2]);
}, $data);
PHP Demo: https://3v4l.org/I82Gt
Regex Demo: https://regex101.com/r/tTcJSp/1/
Try with this. Just replace "," with "." and it's working.
$data = '10 x 2,5';
$data = str_replace(',','.','10 x 2,5');
$array = explode("x", $data);
echo $total = $array[0]*$array[1];
try this:
<?php
$data = '10 x 2,5';
$array = explode("x", $data);
$total = floatval(str_replace(',', '.', $array[0]))*floatval(str_replace(',', '.', $array[1]));
?>
here str_replace() is used to check if there are ,
in the string and then convert into its float value.
Hope this helps.
$data = '10 x 2,5';
$array = explode("x", $data);
$decimal =$array[1];
//replace the comma with dot
$decimal_formated = str_replace(',', '.', $decimal);
//format the string to float
$decimal_formated = (float)$decimal_formated;
//OR $decimal_formated = floatval($decimal_formated);
//get total
$total = $array[0]*$decimal_formated;
//french format $total, with comma
$total_with_comma =number_format($total, 1, ',', ' ');
echo $decimal.'</br>'; //output 2,5
echo $decimal_formated.'</br>'; //output 2.5
echo $total.'</br>'; //output 25
echo $total_with_comma.'</br>'; // output 25,0
You can use number_format(), floatval().

Get range letter and number with php

how can I get range for bottom string in php?
M0000001:M0000100
I want result
M0000001
M0000002
M0000003
..
..
..
M0000100
this is what i do
<?php
$string = "M0000001:M0000100";
$explode = explode(":",$string );
$text_one = $explode[0];
$text_two = $explode[1];
$range = range($text_one,$text_two);
print_r($range);
?>
So can anyone help me with this?
This is one of many ways you could do this and this is a little verbose but hopefully it shows you some "steps" to take.
It doesn't check for the 1st number being bigger than the 2nd.
It doesn't check your Range strings start with a "M".
It doesn't have all of the required comments.
Those are things for you to consider and work out...
<?php
$string = "M00000045:M000099";
echo generate_range_from_string($string);
function generate_range_from_string($string) {
// First explode the two strings
$explode = explode(":", $string);
$text_one = $explode[0];
$text_two = $explode[1];
// Remove the Leading Alpha character
$range_one = str_replace('M', '', $text_one);
$range_two = str_replace('M', '', $text_two);
$padding_length = strlen($range_one);
// Build the output string
$output = '';
for ( $index = (int) $range_one; $index <= (int) $range_two; $index ++ ) {
$output .= 'M' . str_pad($index, $padding_length, '0', STR_PAD_LEFT) . '<br>';
}
return $output;
}
The output lists a String in the format you have specified in the question. So this is based solely upon that.
This could undergo a few more revisions to make it more function like, as I'm sure some folks will pick out!

PHP Image counter number formatting

I'm building a counter that counts and displays on a web page the number of images in a certain directory.
The code I'm currently using is this:
<?
$d = opendir("images/myimagefolder");
$count = 0;
$min_digits = 7;
while(($f = readdir($d)) !== false)
if(ereg('.jpg$', $f))
++$count;
closedir($d);
if ($min_digits)
{
$count = sprintf('%0'.$min_digits.'f', $count);
}
$number = $count;
$formattedNumber = sprintf("%07d", $number);
$formattedNumber = str_split($formattedNumber, 3);
$formattedNumber = implode(",", $formattedNumber);
print "$formattedNumber";
?>
This works well and outputs a number like the following: 000,000,5
What I am wanting is to have the separating commas occur every 3 digits from the right not the left, so it would appear as 0,000,005
How would this this be done?
I have tried a number of modifications to my sprintf and str_split code but nothing has worked so far. Any help would be greatly appreciated!
<?php
//image count
$images=count(glob("images/myimagefolder/*.jpg"));
//padding
$images=sprintf("%07s",$images);
//commas
$images=strrev(implode(",",str_split(strrev($images),3)));
//outputs 0,000,005
echo $images;
?>
Had a bit of fun coming up with the shortest possible way to accomplish your solution. :)
$formattedNumber = sprintf("%07d", $number);
$formattedNumber = str_split(strrev($formattedNumber), 3);
for (i=0;i<count($formattedNumber); i++)
$formattedNumber[i] = strrev($formattedNumber[i]);
$formattedNumber = implode(",", array_reverse($formattedNumber));
Drop the last four lines. All you need is 'print number_format ($count);'
http://php.net/manual/en/function.number-format.php
Edit, the above won't work with the leading 0's
I found this in the comments on the php site. A little regex magic should do it in one line.
print preg_replace("/(?<=\d)(?=(\d{3})+(?!\d))/",",",$count);
Here's my take with arrays:
$num = sprintf("%07d", 5);
$digits = str_split($num, 1);
$digits = array_reverse($digits);
$chunks = array_map('array_reverse', array_reverse(array_chunk($digits, 3)));
$concat_chunks = array();
foreach ($chunks as $chunk) {
$concat_chunks[] = join('', $chunk);
}
$output = join(',', $concat_chunks);
print $output;

PHP string manipulation - manipulate date string in PHP for uploading to mysql

My String:
10:44 13/7
What I require:
2012-07-13
Is there a way I can do this??? The year will always be the current year.
At present, I have:
$string = '10:44 13/7';
$string = explode("/", $string);
$date = date('Y') . '-' . $string[0] . '-'. $string[1];
Many thanks
Thanks to itsme for solution:
$updated = explode(" ", $updated);
$updated[1] = explode("/", $updated[1]);
$y = date('Y');
$m = $updated[1][1];
$d = $updated[1][0];
$updated = $y . '-' . $m . '-' . $d;
echo $updated;
I think rating this question down is a bit harsh... Some of us are not as pro at string manipulation as others and are just getting to grips with PHP. If you want to mark this question down, maybe stackoverflow is not for you or you should just go and try answering the hardcore questions as opposed to making people trying to learn feel small. Yes you know who you are.
Probably a shorter way, but this will work for you:
$string = '10:44 13/7';
list($junk, $date) = explode(' ', $string);
list($day, $month) = explode('/', $date);
$full_date = date('Y-m-d', strtotime(date('Y') . "-{$month}-{$day}"));
echo $full_date; //2012-07-13
Not the most elegant way, but it should work:
$string = "10:44 13/7/" + date("y");
echo date("y-m-d", strtotime($string));

Replacing last x amount of numbers

I have a PHP variable that looks a bit like this:
$id = "01922312";
I need to replace the last two or three numbers with another character. How can I go about doing this?
EDIT Sorry for the confusion, basically I have the variable above, and after I'm done processing it I'd like for it to look something like this:
$new = "01922xxx";
Try this:
$new = substr($id, 0, -3) . 'xxx';
Result:
01922xxx
You can use substr_replace to replace a substring.
$id = substr_replace($id, 'xxx', -3);
Reference:
http://php.net/substr-replace
function replaceCharsInNumber($num, $chars) {
return substr((string) $num, 0, -strlen($chars)) . $chars;
}
Usage:
$number = 5069695;
echo replaceCharsInNumber($number, 'xxx'); //5069xxx
See it in action here: http://codepad.org/XGyVQ1hk
Strings can be treated as arrays, with the characters being the keys:
$id = 1922312; // PHP converts 01922312 => 1 because of that leading zero. Either make it a string or remove the zero.
$id_str = strval($id);
for ($i = 0; $i < count($id_str); $i++)
{
print($id_str[$i]);
}
This should output your original number. Now to do stuff with it, treat it as a normal array:
$id_str[count($id_str) - 1] = 'x';
$id_str[count($id_str) - 2] = 'y';
$id_str[count($id_str) - 3] = 'z';
Hope this helps!
Just convert to string and replace...
$stringId = $id . '';
$stringId = substr($id, 0, -2) . 'XX';
We can replace specific characters in a string using preg_replace(). In my case, I want to replace 30 with 50 (keep the first two digits xx30), in the $start_time which is '1030'.
Solution:
$start_time = '1030';
$pattern = '/(?<=\d\d)30/';
$start_time = preg_replace($pattern, '50', $start_time);
//result: 1050

Categories