Delimited Filename Parsed into Table Row Data - php

I am attempting to convert variable width, pipe (|) delimited file names into table data.
E.g.
var1|var2|var3|var4|var5.pdf
becomes
<table border="2" bordercolor="#ffffff" width="100%" cellpadding="10" cellspacing="10">
<tr>
<td>$var1</td>
<td>$var2</td>
<td>$var3</td>
<td>$var4</td>
<td>$var5</td>
</tr>
</table>
I have everything up to, and after var1 but cannot figure out how to parse the remaining variables out.
This is where I have tossed the towel and decided to post here:
$var1 = substr($file_name, 0, strpos($file_name, '|'));
Ideas?
Thank you in advance!

Maybe you can put all the fields in an array using explode(), like this:
PHP
<?php
$data = "var1|var2|var3|var4|var5.pdf";
$fields = explode("|", $data);
var_dump($fields);
?>
OUTPUT
array(5) { [0]=> string(4) "var1" [1]=> string(4) "var2" [2]=> string(4) "var3" [3]=> string(4) "var4" [4]=> string(8) "var5.pdf" }

You can use list() in conjuction with explode() if you want each value in its separate variable, like this:
list($var1,$var2,$var3,$var4,$var5) = explode('|', $filename);

I suggest that you explode the filenames into an array rather than creating variables for each one, but I have given example code on how to achieve this anyway. I hope I answered your question correctly.
<?php
$string = 'var1|var2|var3|var4|var5.pdf';
// Trim the string of dangling pipes to make sure we don't get empty array elements.
$string = trim($string, '|');
// Split the filenames into an array. Much more managable that way.
$filenames = explode('|', $string);
// Define an empty array to put our variables in.
$variables = array();
// Because the array we made is not associative we can iterate through with a for loop.
for($i = 0; $i < count($filenames); $i++) {
// Make our variable names start from one; much more human-friendly. Add them to an array to extract later.
$var_name = 'var' . ($i + 1);
$variables[$var_name] = $filenames[$i];
}
// Extract the values of the array and place them into variables named after the array keys.
extract($variables, EXTR_OVERWRITE);
This will create the following variables (along with their values).
$var1 = 'var1';
$var2 = 'var2';
$var3 = 'var3';
$var4 = 'var4';
$var5 = 'var5.pdf';

You're looking for the explode() function.
$parts_arr = explode('|', $filename);
var_dump($parts_arr);
Also, pipes are special characters in just about every shell I can think of, I strongly recommend not using them in a file name.

Related

PHP string with int or float to number

If I have two strings in an array:
$x = array("int(100)", "float(2.1)");
is there a simple way of reading each value as the number stored inside as a number?
The reason is I am looking at a function (not mine) that sometimes receives an int and sometimes a float. I cannot control the data it receives.
function convertAlpha($AlphaValue) {
return((127/100)*(100-$AlphaValue));
}
It causes an error in php
PHP Notice: A non well formed numeric value encountered
which I want to get rid of.
I could strip the string down and see what it is and do an intval/floatval but wondered if there was a neat way.
UPDATE:
Playing about a bit I have this:
function convertAlpha($AlphaValue)
{
$x = explode("(", $AlphaValue);
$y = explode(")", $x[1]);
if ($x[0] == "int") {
$z = intval($y[0]);
}
if ($x[0] == "float") {
$z = floatval($y[0]);
}
return((127/100)*(100-$z)); }
This which works but it just messy.
<?php
$x = array("int(100)", "float(2.1)");
$result = [];
foreach($x as $each_value){
$matches = [];
if(preg_match('/^([a-z]+)(\((\d+(\.\d+)?)\))$/',$each_value,$matches)){
switch($matches[1]){
case "int": $result[] = intval($matches[3]); break;
case "float": $result[] = floatval($matches[3]);
}
}
}
print_r($result);
OUTPUT
Array
(
[0] => 100
[1] => 2.1
)
The simplest would simply be to make the array as you need it, so instead of
$x = array("int(100)", "float(2.1)");
you have:
$x = [100, 2.1];
but as this is not what you want you got two choices now. One, is to use eval(), for example:
$x = ['(int)100', '(float)2.1'];
foreach ($x as $v) {
var_dump(eval("return ${v};"));
}
which will produce:
int(100)
double(2.1)
As you noticed, source array is bit different because as there is no such function in PHP as int() or float(), so if you decide to use eval() you need to change the string to be valid PHP code with the casting as shown in above example, or with use of existing intval() or floatval() functions. Finally, you can parse strings yourself (most likely with preg_match()), check for your own syntax and either convert to PHP to eval() it or just process it in your own code, which usually is recommended over using eval().
The way I would do it is by using a regex to determine the type and value by 2 seperate groups:
([a-z]+)\((\d*\.?\d*)\)
The regex captures the alphanumeric characters up and until the first (. It then looks for the characters between the ( and ) with this part: \d*\.?\d*.
The digit-part of the regex accepts input like: 12.34, .12, 12. and 123
$re = '/([a-z]+)\((\d*\.?\d*)\)/m';
$input_values = array('int(100)', 'float(2.1)');
foreach($input_values as $input) {
preg_match_all($re, $input, $matches, PREG_SET_ORDER, 0);
var_dump($matches);
}
Which leads to the output below. As you can see, there is the type in the [1] slot and the number in the [2] slot of the array
array(1) {
[0]=>
array(3) {
[0]=>
string(8) "int(100)"
[1]=>
string(3) "int"
[2]=>
string(3) "100"
}
}
array(1) {
[0]=>
array(3) {
[0]=>
string(10) "float(2.1)"
[1]=>
string(5) "float"
[2]=>
string(3) "2.1"
}
}
You can then use a check to perform the casting like:
$value;
if(matches[1] === "int") {
$value = intval($matches[2]);
} elseif (matches[1] === "float") {
$value = floatval($matches[2]);
}
The latter code still needs error handling, but you get the idea. Hope this helps!
PHP is historically typed against strings so it's pretty strong with cases like these.
$x = array("int(100)", "float(2.1)");
^^^ ^^^
You can actually turn each of those strings into a number by multiplying the substring starting after the first "(" with just one to turn it into a number - be it integer or float:
$numbers = array_map(function($string) {
return 1 * substr(strstr($string, '('), 1);
}, $x);
var_dump($numbers);
array(2) {
[0] =>
int(100)
[1] =>
double(2.1)
}
That is PHP takes everthing numberish from a string until that string seems to end and will calculate it into either an integer or float (var_dump() shows float as double). It's just consuming all number parts from the beginning of the string.
Not saying existing answers are wrong per-se, but if you ask that as a PHP question, PHP has a parser very well for that. My suggestion is to just remove the superfluous information from the beginning of the string and let PHP do the rest.
If you want it more precise, regular expressions are most likely your friend as in the yet top rated answer, still combined with PHP will give you full checks on each string:
$numbers = array_map(function($string) {
$result = preg_match('~^(?:int|float)\(([^)]+)\)$~', $string, $group) ? $group[1] : null;
return null === $result ? $result : 1 * $result;
}, $x);
So all non int and float strings will be turned into NULLs (if any).

store string with key and value in array

I have a string = "Name":"Susan","Age":"23","Gender":"Male";
How to store them in an array so that I can echo the value for example:
echo $array['Name']
or
echo $array['Age']
Thanks
If your string is already:
"Name":"Susan","Age":"23","Gender":"Male"
That's almost JSON, so you can just enclose it in curly brackets and convert it to turn that into an array:
$decoded = (Array)json_decode('{'.$str.'}');
json_decode() normally outputs an object, but here we're casting it to an array. This is not required, but it changes how you have to access the resulting elements.
This would render the following associative array:
array(3) {
["Name"]=>
string(5) "Susan"
["Age"]=>
string(2) "23"
["Gender"]=>
string(4) "Male"
}
Associative Arrays in PHP are what you need to achieve your task. In PHP array() are actually ordered maps i.e. associates values with a key Here is an example. An associative array is an array where each key has its own specific value. Here's an example.
$values = array("Name"=>"Susan", "Age"=>"23", "Gender"=>"Male");
echo $values['Name'];
echo $values['Age'];
echo $values['Gender'];
You can store string as json
$json = '{"Name":"Susan","Age":"23","Gender":"Male"}';
$array = json_decode($json, true);
var_dump($array);
The manual specifies the second argument of json_decode as:
assoc
When TRUE, returned objects will be converted into associative arrays.
https://stackoverflow.com/a/18576902/5546916
Try below snippet
$string = "Name":"Susan","Age":"23","Gender":"Male";
//explode string with `,` first
$s = explode(",",$string); // $s[0] = "Name":"Susan"....
$array = array();
foreach($s as $data){
$t = array();
$t = explode(":",$data); //explode with `:`
$array[$t[0]] = $t[1];
}
echo $array["name"];

Using an array from a single cookie value as PHP array

I'm trying to use this cookie - current=["1","2","4"] - as a usable array in PHP.
At the moment I can echo these values, but can't use them as an array. How would I convert these values into a usable PHP array?
$currentUsers = $_COOKIE['current'];
echo $currentUsers;
print_r(array_values($currentUsers));
$array = explode(",",$currentUsers);
Var_dump($array);
Echo $array[0]; // 1
Echo $array[1]; // 2
Echo $array[2]; // 4
Edit: Not sure if the " is actually a part of the cookie values?
If it is you could use str_replace('"', '', $currentUsers); to remove the " from the values if you do it before the explode.
Edit2: as Ash pointed out I missed a part on the answer.
Here is the complete code:
$str = substr(str_replace('"', '', $currentUsers),1,-1);
$array = explode(",",$str);
Var_dump($array);
Echo $array[0]; // 1
Echo $array[1]; // 2
Echo $array[2]; // 4
Another solution, if the values are always numbers as in the example:
preg_match_all("/(\d+)/", $currentUsers, $array);
Simple one liner. IF it's always numbers
Working example http://www.phpliveregex.com/p/fuO
Click preg match all button first
Use eval()
$current = [];
eval('$'.$currentUsers);
var_dump($current);
For those with lightweight downvote, the output:
[root#mypc]# php test.php
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "4"
}

PHP Array with multiple lines

I have an array that looks like the example below. How to I get only the value in the first line (the audio file path)? I have already tried array_rand() which only gives me values letter by letter. Sorry if this has been answered before, couldn't find anything myself. Thanks in advance.
Array
(
[0] => path/to/audiofile.mp3
3500440
audio/mpeg
[1] => path/to/anotheraudiofile.mp3
5661582
audio/mpeg
...
)
Edit: var_dump gives me this:
array(2) {
[0]=>
string(98) "path/to/audiofile.mp3
3500440
audio/mpeg
"
[1]=>
string(95) "path/to/anotheraudiofile.mp3
5661582
audio/mpeg
"
}
Have you tried to split on line return ?
$tmp = explode(PHP_EOL, $myArray[0]);
$tmp = explode('"', $tmp[0]);
$path = $tmp[1];
The real solution would be to alter the code that is actually constructing this array, however, you can easily extract what you need with a couple array function (of which there are many):
$array[0] = explode(PHP_EOL, $array[0]);//PHP_EOL is the new-line character
echo $array[0][0];//get the first line
You can process the entire array like so:
function extractFirstLine($val)
{
$val = explode(PHP_EOL, $val);
return $val[0];
}
$array = array_map('extractFirstLine', $array);
Or, since PHP 5.3 the more common approach:
$array = array_map(function($v)
{
$v = explode(PHP_EOL, $v);
return $v[0];
}, $array);
And since PHP 5.4, you can write this even shorter:
$array = array_map(function($v)
{
return (explode(PHP_EOL, $v))[0];
}, $array);
That ought to do it (Note, this code is untested, but the man pages should help you out if something isn't quite right).
B"e aware of it depends on the os Line maybe diffrent character, you may use \r\n if you using a win os
$Path = substr($array[0] , 0 , strpos("\n",$array[0]))

Array by expressions

In php I have the following variable which comes from a url:
$data = "data_id=value1/config/value2/config/value3";
It always comes in the following format:
data_id = first value of the parameter to come
/ config / -> which is a kind of parameters tab
second parameter + / config / + etc ...
I want these values ​​to be inserted into an array, i.e., what would happen is the following:
The Wrath php gets the variable $data, would catch the first parameter, in this case e.g. value1 (which'll come after the data_id) and insert it into the array as a vector 1, soon after it takes the / config / and recognizes that it is a separator, thus making it take the value 2 and enter the array, making this loop until the end.
example:
$data = "data_id =fish/config/horse/config/car";
The array will look as follows:
array
{
[0] -> fish
[1] -> horse
[2] -> Car
}
could someone help me?
Assuming data_id is a GET variable, you can do something like this.
$data = $_GET['data_id']
$myArray = explode('/config/', $data);
explode() documentation
<?php
$data = 'data_id=value1/config/value2/config/value3';
list($name, $value) = explode('=', $data, 2);
$result = explode('/config/', $value);
print_r($result);
Example
If the entire thing is a string you can use strpos to get the position of the = character and cut it away using substr. Then simply explode the entire thing with php explode.
$data = "data_id =fish/config/horse/config/car";
$data = explode( "/config/", substr( $data, strpos( $data, '=' )+1 ) );
Will result in:
array(3) {
[0]=>
string(4) "fish"
[1]=>
string(5) "horse"
[2]=>
string(3) "car"
}
strpos()
substr()
explode()

Categories