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;
?>
Related
I want to define two new variables as the longest strings from a given string. if the string does not contain any dashes, just choose it for both.
Example:
$orig=`welcome-to-your-world`
$s1=`welcome`
$s2=`world`
$orig=`welcome-to-your-holiday`
$s1=`welcome` // order not important
$s2=`holiday`// order not important
$orig=`welcome`
$s1=`welcome`
$s2=`welcome`
Solution with explode and sorting result array by length of words:
$orig = 'welcome-to-your-world';
$parts = explode('-', $orig);
if (1 < count($parts)) {
usort($parts, function($a, $b) { return strlen($a) < strlen($b); });
$s1 = array_shift($parts);
$s2 = array_shift($parts);
} else {
$s1 = $s2 = $orig;
}
echo $s1 . PHP_EOL . $s2;
Fiddle here.
It seems like your string is in dash-case (words in lower case separated by dashes).
So, you can do the following:
// convert origin in an array
$origin_array = explode("-", $origin);
//retrivies the first element from array
$s1 = '';
$s2 = '';
// get the longest string
foreach($origin_array as $word) {
if(strlen($word) > strlen($s1)) {
$s1 = $word;
}
}
// remove the longest word from the array
$origin_array = array_diff($origin_array, [$s1]);
// get the second longest string
foreach($origin_array as $word) {
if(strlen($word) > strlen($s2)) {
$s2 = $word;
}
}
I think that solves your problem. Hope that helps!
Note: This method is not efficient because it runs foreach twice. The other answer is better if you care about performance.
$orig = 'welcome-to-your-world';
$array = explode('-', $orig);
$lengths = array_map('strlen', $array);
$s1key = array_search(max($lengths), $lengths);
$s1 = $array[$s1key];
unset ($array[$s1key], $lengths[$s1key]);
$s2key = array_search(max($lengths), $lengths);
$s2 = $array[$s2key];
I want to parse and expand the given strings in PHP.
From
0605052&&-5&-7&-8
0605052&&-4&-7
0605050&&-2&-4&-6&-8
To
0605052, 0605053 ,0605054 ,0605055, 0605057, 0605058
0605052,0605053,0605054,0605057
0605050,0605051,0605052,0605054,0605056,0605058
can someone help me with that? thanks in advance!
Your question is not very clear, but I think you mean a solution like this:
Edited: Now the hole ranges were shown and not only the specified numbers.
<?php
$string = "0605052&&-5&-7&-8";
$test = '/^([0-9]+)\&+/';
preg_match($test, $string, $res);
if (isset($res[1]))
{
$nr = $res[1];
$test = '/\&\-([0-9])/';
preg_match_all($test, $string, $res);
$result[] = $nr;
$nrPart = substr($nr, 0, -1);
$firstPart = substr($nr, -1);
if (isset($res[1]))
{
foreach ($res[1] as &$value)
{
if ($firstPart !== false)
{
for ($i=$firstPart+1; $i<=$value; $i++)
{
$nr = $nrPart . $i;
$result[] = $nr;
}
$firstPart = false;
}
else
{
$nr = $nrPart . $value;
$result[] = $nr;
$firstPart = $value;
}
}
}
var_dump($result);
}
?>
This delivers:
result[0] = "0605052"
result[1] = "0605053"
result[2] = "0605054"
result[3] = "0605055"
result[4] = "0605057"
result[5] = "0605058"
I think a multi step approach is the best thing to do here.
E.g. take this as an example 0605052&&-5&-7&-8:
Split at -. The result will be 0605052&&, 5&, 7&, 8
The first result 0605052&& will help you create your base. Simply substring the numbers by finding first occurence of & and substring to the next to last number. Result will be 060505. You will also need the last number, so get it as well (which is 2 in this case).
Get the remaining ends now, all \d& are simple to get, simply take the first character of the string (or if those can be more than one number, use substring with first occurence of & approach again).
The last number is simple: it is 8.
Now you got all important values. You can generate your result:
The last number from 2., all numbers from 3. and the number from 4. together with your base are the first part. In addition, you need to generate all numbers from the last number of 2. and the first result of 3. in a loop by a step of 1 and append it to your base.
Example Code:
<?php
$str = '0605052&&-5&-7&-8';
$split = explode('-', $str);
$firstAmpBase = strpos($split[0], '&');
$base = substr($split[0], 0, $firstAmpBase - 1);
$firstEnd = substr($split[0], $firstAmpBase - 1, 1);
$ends = [];
$firstSingleNumber = substr($split[1], 0, strpos($split[1], '&'));
for ($i = $firstEnd; $i < $firstSingleNumber; $i++) {
array_push($ends, $i);
}
array_push($ends, $firstSingleNumber);
for ($i = 2; $i < count($split) - 1; $i++) {
array_push($ends, substr($split[$i], 0, strpos($split[$i], '&')));
}
array_push($ends, $split[count($split) - 1]);
foreach ($ends as $end) {
echo $base . $end . '<br>';
}
?>
Output:
0605052
0605053
0605054
0605055
0605057
0605058
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)));
how can i convert it into float and then increment it and then convert back to string.
if($set==$Data_Id)
{
$rel='1.1.1.2';
}
after increment it should be like 1.1.1.3.
Please any help.
so crazy, it may work
$rel='1.1.1.2';
echo substr($rel, 0, -1). (substr($rel,-1)+1); //1.1.1.3
the big question is what do you want to happen if the string ends in 9 ??
Here's a slightly different approach.
<?php
function increment_revision($version) {
return preg_replace_callback('~[0-9]+$~', function($match) {
return ++$match[0];
}, $version);
}
echo increment_revision('1.2.3.4'); //1.2.3.5
Anthony.
"1.1.1.2" is not a valid number. So you'll have to do something like this:
$rel = '1.1.1.2';
$relPlusOne = increment($rel);
function increment($number) {
$parts = explode('.', $number);
$parts[count($parts) - 1]++;
return implode('.', $parts);
}
If this is exactly the case you need to solve, you could do it with intval(), strval(), str_replace(), substr() and strlen().
$rel = '1.1.1.2'; // '1.1.1.2'
// replace dots with empty strings
$rel = str_replace('.', '', $rel); // '1112'
// get the integer value
$num = intval($rel); // 1112
// add 1
$num += 1; // 1113
// convert it back to a string
$str = strval($num); // '1113'
// initialize the return value
$ret = '';
// for each letter in $str
for ($i=0; $i<strlen($str); $i++) {
echo "Current ret: $ret<br>";
$ret .= $str[$i] . '.'; // append the current letter, then append a dot
}
$ret = substr($ret, 0, -1); // remove the last dot
echo "Incremented value: " . $ret;
This method will change 1.1.1.9 to 1.1.2.0, however. If that's what you want, then this will be fine.
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