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
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 am trying to extract a string in php and convert them to comma separated strings
Here are some sample string I am working with and the results I need:
input :
G1_C2_S3_T5 or G4_C5_S4_T7_I6_H3
Result must be :
G1,G1_C2,G1_C2_S3,G1_C2_S3_T5
or
G4,G4_C5,G4_C5_S4,G4_C5_S4_T7,G4_C5_S4_T7_I6,G4_C5_S4_T7_I6_H3
Input length can be dynamic for comma separation
Is this correct :
$arr = explode("_", $string, 2);
$first = $arr[0];
How can i do that in php?
Something like this should work, $string is the string you are working with
//explode by underscore
$parts = explode('_', $string);
$c = [];
//do until nothing else to pop from array
while (!empty($parts)) {
$c[] = implode('_', $parts);
//will pop element from end of array
array_pop($parts);
}
//reverse
$c = array_reverse($c);
//glue it with comma
echo implode(',', $c);
You should notice that the number of underscore-separated values in your initial string e.g. G4_C5_S4_T7_I6_H3 (6) is equal to the number of comma-separated values in your desired string e.g. G4,G4_C5,G4_C5_S4,G4_C5_S4_T7,G4_C5_S4_T7_I6,G4_C5_S4_T7_I6_H3 (6). So we'll use this number in our first loop $end = count($parts).
$str = "G4_C5_S4_T7_I6_H3";
$newstr = '';
$parts = explode('_', $str);
$comma = '';
for ($i = 0, $end = count($parts); $i < $end; $i++) {
$newstr .= $comma;
$underscore = '';
// build underscore-separated value
// index i is used to indicate up which value to stop at for each iteration
for ($j = 0; $j <= $i; $j++) {
$newstr .= $underscore . $parts[$j];
// set underscore after the first iteration of the loop
$underscore = '_';
}
// set comma after the first iteration of the loop
$comma = ',';
}
echo $newstr; // G4,G4_C5,G4_C5_S4,G4_C5_S4_T7,G4_C5_S4_T7_I6,G4_C5_S4_T7_I6_H3
The explosion is easy:
$parts = explode('_', $string);
Now you get a $parts array like [ 'G1', 'C2', 'S3', 'T5' ].
You want to convert this to an array so that each item is the concatenation of that item and every other item before it:
$prev = [ ];
array_walk(
$parts,
function(&$value) use (&$prev) {
$prev[] = $value;
$value = implode('_', $prev);
}
);
Now $parts holds the elements:
print implode(', ', $parts);
yields
G1, G1_C2, G1_C2_S3, G1_C2_S3_T5
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
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;
}
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)));