I want to insert a new line after n commas.
For example I got this value: 385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426
How I could echo them all, but every 5th comma there should be a linebreak?
385,386,387,388,389,
390,391,392,393,394,
395,396,397,398,399,
400,401,402,403,404,
405,406,407,408,409,
410,411,412,413,414,
415,416,417,418,419,
420,421,422,423,424,
425,426
Here's one method:
// Get all numbers
$numbers = explode(',', $str);
// Split into groups of 5 (n)
$lines = array_chunk($numbers, 5);
// Format each line as comma delimited
$formattedLines = array_map(function ($row) { return implode(',', $row); }, $lines);
// Format groups into new lines with commas at the end of each line (except the last)
$output = implode(",\n", $formattedLines);
Try this
<?php
//Start //Add this code if your values in string like that
$string = "385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426";
$string_array = explode(',', $string);
//End //Add this code if your values in string like that
//If you have values in array then direct use below code skip above code and replace $string_array variable with yours
end($string_array);
$last = key($string_array);
foreach ($string_array as $key => $value) {
if($last==$key){
echo $value;
}else{
echo $value.',';
}
if(($key+1)%5==0){
echo "<br />";
}
}
?>
Try like this.
You can explode the string with commas and check for every 5th
position there should be a line break.
You can check it with dividing key with 5.(i.e) it will give you a
remainder of 0
Please note that key starts from 0, so I have added (key+1), to make it start from 1
$string = "385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426";
$stringexplode = explode(",", $string);
$countstringexplode = count($stringexplode);
foreach($stringexplode as $key => $val)
{
$keyIncrement = $key+1;
echo $val.($countstringexplode == $keyIncrement ? "" : ",") ;
if(($keyIncrement) % 5 == 0)
echo "<br>";
}
?>
Related
I have a long string variable that contains coordinates
I want to keep each coordinate in a separate cell in the array according to Lat and Lon..
For example. The following string:
string = "(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)";
I want this:
arrayX[0] = "33.110029967689556";
arrayX[1] = "33.093492845160036";
arrayX[2] = "33.0916232355565";
arrayY[0] = "35.60865999564635";
arrayY[1] = "35.63955904349791";
arrayY[2] = "35.602995170206896";
Does anyone have an idea ?
Thanks
Use substr to modify sub string, it allow you to do that with a little line of code.
$array_temp = explode('),', $string);
$arrayX = [];
$arrayY = [];
foreach($array_temp as $at)
{
$at = substr($at, 1);
list($arrayX[], $arrayY[]) = explode(',', $at);
}
print_r($arrayX);
print_r($arrayY);
The simplest way is probably to use a regex to match each tuple:
Each number is a combination of digits and .: the regex [\d\.]+ matches that;
Each coordinate has the following format: (, number, ,, space, number,). The regex is \([\d\.]+,\s*[\d\.]+\).
Then you can capture each number by using parenthesis: \(([\d\.]+),\s*([\d\.]+)\). This will produce to capturing groups: the first will contain the X coordinate and the second the Y.
This regex can be used with the method preg_match_all.
<?php
$string = '(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)';
preg_match_all('/\(([\d\.]+)\s*,\s*([\d\.]+)\)/', $string, $matches);
$arrayX = $matches['1'];
$arrayY = $matches['2'];
var_dump($arrayX);
var_dump($arrayY);
For a live example see http://sandbox.onlinephpfunctions.com/code/082e8454486dc568a6557058fef68d6f10c8dbd0
My suggestion, working example here: https://3v4l.org/W99Uu
$string = "(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)";
// Split by each X/Y pair
$array = explode("), ", $string);
// Init result arrays
$arrayX = array();
$arrayY = array();
foreach($array as $pair) {
// Remove parentheses
$pair = str_replace('(', '', $pair);
$pair = str_replace(')', '', $pair);
// Split into two strings
$arrPair = explode(", ", $pair);
// Add the strings to the result arrays
$arrayX[] = $arrPair[0];
$arrayY[] = $arrPair[1];
}
You need first to split the string into an array. Then you clean the value to get only the numbers. Finally, you put the new value into the new array.
<?php
$string = "(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)";
$loca = explode(", ", $string);
$arr_x = array();
$arr_y = array();
$i = 1;
foreach($loca as $index => $value){
$i++;
if ($i % 2 == 0) {
$arr_x[] = preg_replace('/[^0-9.]/', '', $value);
}else{
$arr_y[] = preg_replace('/[^0-9.]/', '', $value);
}
}
print_r($arr_x);
print_r($arr_y);
You can test it here :
http://sandbox.onlinephpfunctions.com/code/4bf04e7aabeba15ecfa114d8951eb771610a43a4
I have a string of delimited numerical values just like this:
5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004| ...etc.
Depending on the circumstance, the string may have only 1 value, 15 values, all the way up to 100s of values, all pipe delimited.
I need to count off (and keep/echo) the first 10 values and truncate everything else after that.
I've been looking at all the PHP string functions, but have been unsuccessful in finding a method to handle this directly.
Use explode() to separate the elements into an array, then you can slice off the first 10, and implode() them to create the new string.
$arr = "5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004";
$a = explode ('|',$arr);
$b = array_slice($a,0,10);
$c = implode('|', $b);
Use PHP Explode function
$arr = explode("|",$str);
It will break complete string into an array.
EG: arr[0] = 5, arr[1] = 2288 .....
I would use explode to separate the string into an array then echo the first ten results like this
$string = "5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004";
$arr = explode("|", $string);
for($i = 0; $i < 10; $i++){
echo $arr[$i];
}
Please try below code
$str = '5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324';
$arrayString = explode('|', $str);
$cnt = 0;
$finalVar = '';
foreach ($arrayString as $data) {
if ($cnt > 10) {
break;
}
$finalVar .= $data . '|';
$cnt++;
}
$finalVar = rtrim($finalVar, '|');
echo $finalVar;
I've been trying to figgure out using substr, rtrim and it keeps removing all the commas. And if it doesn't nothing shows up. So I am basicly stuck and require some help.. Would've been apriciated.
if(is_array($ids)) {
foreach($ids as $id) {
$values = explode(" ", $id);
foreach($values as $value) {
$value .= ', ';
echo ltrim($value, ', ') . '<br>';
}
}
}
I am guessing that you are trying to take an array of strings of space separated ids and flatten it into a comma separated list of the ids.
If that is correct you can do it as:
$arr = [
'abc def ghi',
'jklm nopq rstu',
'vwxy',
];
$list = implode(', ', explode(' ', implode(' ', $arr)));
echo $list;
output:
abc, def, ghi, jklm, nopq, rstu, vwxy
Change ltrim by rtrim:
ltrim — Strip whitespace (or other characters) from the beginning of a string
rtrim — Strip whitespace (or other characters) from the end of a string
<?php
$ids = Array ( 1,2,3,4 );
$final = '';
if(is_array($ids)) {
foreach($ids as $id) {
$values = explode(" ", $id);
foreach($values as $value) {
$final .= $value . ', ';
}
}
echo rtrim($final, ', ') . '<br>';
echo substr($final, 0, -2) . '<br>'; //other solution
}
?>
If your array looks like;
[0] => 1,
[1] => 2,
[2] => 3,
...
The following should suffice (not the most optimal solution);
$string = ''; // Create a variable to store our future string.
$iterator = 0; // We will need to keep track of the current array item we are on.
if ( is_array( $ids ) )
{
$array_length = count( $ids ); // Store the value of the arrays length
foreach ( $ids as $id ) // Loop through the array
{
$string .= $id; // Concat the current item with our string
if ( $iterator >= $array_length ) // If our iterator variable is equal to or larger than the max value of our array then break the loop.
break;
$string .= ", "; // Append the comma after our current item.
$iterator++; // Increment our iterator variable
}
}
echo $string; // Outputs "1, 2, 3..."
Use trim() function.
Well, if you have a string like this
$str="foo, bar, foobar,";
use this code to remove the Last comma
<?Php
$str="foo, bar, foobar,";
$string = trim($str, " ,");
echo $string;
output: foo, bar, foobar
I'm not sure how to better phrase my question, but here is my situation.
I have an array like the following:
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");
I need to loop through this array and try to match the first portion of each string in the array
e.g.
$id = "222222";
$rand_number = "999888";
if ($id match the first element in string) {
fetch this string
append "999888" to "122874|876394|120972"
insert this string back to array
}
So the resulting array becomes:
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-999888|122874|876394|120972", "333333-Name3-122874|876394|120972");
Sorry if my question appears confusing, but it really is pretty difficult for me to even grasp some of the required operations.
Thanks
Try this:
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");
$id = "222222";
$rand_number = "999888";
// Loop over each element of the array
// For each element, $i = the key, $arr = the value
foreach ($temp_array as $i => $arr){
// Get the first characters of the element up to the occurrence of a dash "-" ...
$num = substr($arr, 0, strpos($arr, '-'));
// ...and check if it is equal to $id...
if ($num == $id){
// ...if so, add $random_number to the back of the current array element
$temp_array[$i] .= '|' . $rand_number;
}
}
Output:
Array
(
[0] => 111111-Name1-122874|876394|120972
[1] => 222222-Name2-122874|876394|120972|999888
[2] => 333333-Name3-122874|876394|120972
)
See demo
Note: As Dagon pointed out in his comment, your question says appends, but your example shows the data being prepended. This method appends, but can be altered as necessary.
http://php.net/manual/en/control-structures.foreach.php
http://php.net/manual/en/function.substr.php
http://php.net/manual/en/function.strpos.php
You could also using some exploding in this case too:
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");
$id = "222222";
$rand_number = "999888";
foreach($temp_array as &$line) {
// ^ reference
$pieces = explode('|', $line); // explode pipes
$first = explode('-', array_shift($pieces)); // get the first part, explode by dash
if($first[0] == $id) { // if first part is equal to id
$first[2] = $rand_number; // replace the third part with random
$first = implode('-', $first); // glue them by dash again
$line = implode('|', array($first, implode('|',$pieces))); // put them and glue them back together again
}
}
echo '<pre>';
print_r($temp_array);
crude answer - its going to depend on the expected values of the initial ids. if they could be longer or shorter then explode on the hyphen instead of using substr
$temp_array = array("111111-Name1-122874|876394|120972","222222-Name2-122874|876394|120972","333333-Name3-122874|876394|120972");
$id = "222222";
$rand_number = "999888";
foreach($temp_array as $t){
if(substr(0,6,$t)==$id){
$new[] = $t.'|'.$rand_number;
}else{
$new[] = $t;
}
}
Another version using array_walk
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");
$id = "222222";
$rand_number = "999888";
$params = array('id'=>$id, 'rand_number'=>$rand_number);
array_walk($temp_array, function(&$value, $key, $param){
$parts = explode('-', $value); // Split parts with '-' so the first part is id
if ($parts[0] == $param['id']){
$parts[2]="{$param['rand_number']}|{$parts[2]}"; //prepend rand_number to last part
$value=implode('-',$parts); //combine the parts back
}
},$params);
print_r($temp_array);
If you just want to append The code becomes much shorter
$params = array('id'=>$id, 'rand_number'=>$rand_number);
array_walk($temp_array, function(&$value, $key, $param){
// here check if the first part of the result of explode is ID
// then append the rand_number to the value else append '' to it.
$value .= (explode('-', $value)[0] == $param['id'])? "|{$param['rand_number']}" : '';
},$params);
Edit: Comments added to code.
I am collecting html text area data to echo in php.I am able to select all data using
$devices = explode("\n", $_POST['devs']);
foreach($devices as $device)
echo $device;
and I am able to select only the first line using:
$first_line = strstr(($_POST['devs']), "\n", true);
echo $first_line;
But How can I echo specific lines ? say line 2 or 4 from text area ?
Usage:
getLines(YOUR POST, START LINE, END LINE(optional));
With return array:
function getLines($text, $start, $end = false)
{
$devices = explode("\n", $text);
$append = "My device is ";
$output = array();
foreach ($devices as $key => $line)
{
if ($key+1 < $start) continue;
if ($end && $key+1 > $end) break;
$output[] = $append.$line;
}
return $output;
}
$array = getLines($_POST['devs'], 2);
var_dump($array);
With echo string:
function getLines($text, $start, $end = false)
{
$devices = explode("\n", $text);
$append = "My device is ";
$output = "";
foreach ($devices as $key => $line)
{
if ($key+1 < $start) continue;
if ($end && $key+1 > $end) break;
$output .= $append.$line."<br />";
}
return $output;
}
echo getLines($_POST['devs'], 2);
Your first code snippet is already creating an array of lines via the explode function.
As such, to output the 2nd and 4th lines, you can simply use:
$devices = explode("\n", $_POST['devs']);
echo $devices[1];
echo $devices[3];
If you're new to PHP (I'm guessing this is the case due to the nature of your question), it should be noted that like many programming languages, arrays are indexed from zero, hence line 2 is 1, line 4 is [3], etc.
UPDATE
To access the penultimate (i.e.: 2nd to last) line, you could use:
echo $devices[count($devices) - 2];
What we're doing here is getting the number of elements in the array (via count) and then subtracting two to fetch the second last element. (As we need to subtract one to deal with the fact that arrays are indexed from zero.)
Do it like this
$nth_line = explode("\n", $_POST['devs'])[n];
where n is you line no.
the explode() returns an array then you can select each element by basic array operation
further readings http://php.net/manual/en/function.explode.php
because $devices is an array after exploding it, you can treat each line by it's index. Reminder that arrays are zero-index based so 1 starts at 0.
$devices = explode('\n', $_POST['devs']);
// line 1
echo $devices[0];
// line 2
echo $devices[1];
// line 4
echo $devices[3];
you can use split:
$lines = split("\n", $_POST['devs']);
echo $lines[3]; //4th line
See documentation http://php.net/manual/es/function.split.php
Take a look at array operations in PHP. Since $devices is an array you can select an element by its index like this: $devices[1] for second element, $devices[2] for third etc.
Lookup your syntax on php.net. It is
$devices = explode(";", "aap;noot;mies");
print_r($devices);
foreach ($devices as $key => $value) {
echo "<br>nr.$key=" . $devices[$key];
}