PHP or javascript: Flip order of text rows (not MySQL) - php

How can I flip the order of text
$string = 'last row
something inbetween
first row';
Result should be:
first row
something inbetween
last row
Note this is no A-Z ordering, just flipping it.
Is it possible? A solution in PHP, javascript or jquery would be welcome

You could explode the string into an array, reverse it and put it back together:
$a=explode("\n",$string);
$string=implode("\n",array_reverse($a));

You can split the string and reverse the array:
$array = explode("\n", $string);
$array = array_reverse($array);
$string = implode("\n", $array);
Edit: no one wrote an javascript solution (same logic as php script):
var string = string.split("\n").reverse().join("\n");
Edit: an example: http://jsfiddle.net/ceKyF/

You only got PHP answers, here is a javascript one:
// Split the string into an array
var arr = string.split( '\n' )
// Reverse the array
arr.reverse()
// Join the array back into a string
string = arr.join( '\n' )
This can be done in one line:
string = string.split( '\n' ).reverse().join( '\n' )

Related

how to input elements instead of another array, into end of array?

Due to bad DB design, there may be several values in a column # each row in a table. So I had to take in every string, check if commas exist (multiple values) & place each element into the end of an array.
Did try out functions like strpos, explode, array_push etc. With the folllowing code, how do i input ONLY the multiple elements into the end of an array, without creating another & placing that into an existing array?
$test = array();
$test = array ("testing");
$str = 'a,b,c,d';
$parts = explode(',', $str);
array_push ($test, $parts); //another array inserted into $test, which is not what I want
print_r($test);
Use array_merge.
$test = array_merge($test, $parts);
Example: http://3v4l.org/r7vaB

Remove characters from string based on user input

Suppose I have a string:
$str="1,3,6,4,0,5";
Now user inputs 3.
I want that to remove 3 from the above string such that above string should become:
$str_mod="1,6,4,0,5";
Is there any function to do the above?
You can split it up, remove the one you want then whack it back together:
$str = "1,3,6,4,0,5";
$userInput = 3;
$bits = explode(',', $str);
$result = array_diff($bits, array($userInput));
echo implode(',', $result); // 1,6,4,0,5
Bonus: Make $userInput an array at the definition to take multiple values out.
preg_replace('/\d[\D*]/','','1,2,3,4,5,6');
in place of \d just place your digit php
If you don't want to do string manipulations, you can split the string into multiple pieces, remove the ones you don't need, and join the components back:
$numberToDelete = 3;
$arr = explode(',',$string);
while(($idx = array_search($numberToDelete, $components)) !== false) {
unset($components[$idx]);
}
$string = implode(',', $components);
The above code will remove all occurrences of 3, if you want only the first one yo be removed you can replace the while by an if.

php array count includes trailing comma

I have an array which I get from an exploded url (using $_GET).
The elements in the url are separated by commas but when I COUNT the elements the result includes the final comma. Eg: '?list=jonny,sally,bob,' returns '4' when '?list=jonny,sally,bob' returns '3'. I can't avoid the final comma as they are genrated with them automatically but I need to return 3 on both examples. Any ideas please?? Thanks
$list = explode(",", $_GET['list']);
$listCount = count($list);
//$listCount =(int)$listCount -1;
//$list[$listCount]=str_replace($list[$listCount],',','');
echo $listCount;
NB: the commented out lines are a failed attempt to remove the comma. But $list[$listCount] ,ie the final array element doesn't seem to exist even though it is counted
If you want to trim any extra commas at the start or end of the string, use trim(). If you want it at the end of the string, you can use rtrim().
$list = explode(",", $_GET['list']);
to
$list = explode(",", trim($_GET['list'], ','));
Trim any commas first:
$strList = rtrim($_GET['list'], ",")
$arrList = explode(",", $strList);
Array_filter will remove any empty values from your array, so in case you have two commas in a row, it will remove empty values caused by that also.
$list = array_filter(explode(",", $_GET['lists']));

Prepend each line of a variable with a string

How can I prepend a string, say 'a' stored in the variable $x to each line of a multi-line string variable using PHP?
Can also use:
echo preg_replace('/^/m', $prefix, $string);
The / are delimiters. The ^ matches the beginning of a string. the m makes it multiline.
demo
There are many ways to achieve this.
One would be:
$multi_line_var = $x.str_replace("\n", "\n".$x, $multi_line_var);
Another would be:
$multi_line_var = explode("\n", $multi_line_var);
foreach($multi_line_var AS &$single_line_var) {
$single_line_var = $x.$single_line_var;
}
$multi_line_var = implode("\n", $multi_line_var);
Or as a deceitfully simple onliner:
$multi_line_var = $x.implode("\n".$x, explode("\n", $multi_line_var));
The second one is dreadfully wasteful compared to the first. It allocates memory for an array of strings. It runs over each array item and modifies it. And the glues the pieces back together.
But it can be useful if one concatenation is not the only alteration you're doing to those lines of text.
Because of your each line requirement, I would first split the string to an array using explode, then loop through the array and add text to the beginning of each line, and then turn the array back to a string using implode. As long as the number of lines is not very big, this can be a suitable solution.
Code sample:
$arr = explode("\n", $x);
foreach ($arr as $key => $value) {
$arr[$key] = 'a' . $arr[$key];
}
$x = implode("\n", $arr);
Example at: http://codepad.org/0WpJ41LE

display from database

while displaying address from database I have added , at the end of each value. when last value of address in empty am getting , along with the last value. But I don't want that. Can any one help?
if ($Fetch['addr']!=''){
echo $Fetch['addr'].',';
it is displaying
address,city,postalcode
if i remove postalcode it displayes
address,city,
but i don't need , at the end when any of the value is not provided
Insert your value in array and at the end of it use join to convert array to string with:
$array[] = [Your Value Here];
$string = join ( ',' , $array )
Store the output in a variable do not echo directly with if as you are doing and then use below function and finally print them after applying rtrim on the $str.
string should be stored in $str with all the if's
if ($Fetch['addr']!=''){
$str.=$Fetch['addr'].',';
This will remove last comma
echo $clean = rtrim($str,',');
Use Substr() It will really helps!
$str = "abcde,";
$str = substr($str,'',-1);
Now this will remove , from String.

Categories