Add <br /> after 3rd symbol in Array - php

I have the following variable:
$checkbox = implode(';', $_POST['product']);
$checkbox is equal to "Product Name;Price;Unit", how can I add a break after every line?
At the moment $checkbox is equal to:
ASFP4040;18.95;1;ASFP4048;21;1;ASGS100100;25.45;1
I need it to be like:
ASFP4040;18.95;1;
ASFP4048;21;1;
ASGS100100;25.45;1;
EDIT:
I am writing this to a .TXT file, \n shows as text and doesn't actually create a new line.

As I'm not sure, how your $_POST['products'] var looks like, you might like one of these options:
If you have everything in a single array element like this
Array
(
[0] => ASFP4040
[1] => 18.95
[2] => 1
[3] => ASFP4048
[4] => 21
[5] => 1
[6] => ASGS100100
[7] => 25.45
[8] => 1
)
you could split the array into chunks and join them together
$data = implode("\n", array_map(function($chunk) {
return implode(';', $chunk);
}, array_chunk($_POST['product'], 3)));
Alternatively, if you have an array of strings like below:
Array
(
[0] => ASFP4040;18.95;1
[1] => ASFP4048;21;1
[2] => ASGS100100;25.45;1
)
a simple implode would be enough
$data = implode("\n", $_POST['product']);

Try this:
echo "'".implode("','",$checkbox)."'<br>";

You can use regular expressions to do this. Just replace my $str with your $checkbox.
$str = 'ASFP4040;18.95;1;ASFP4048;21;1;ASGS100100;25.45;1';
$str2 = preg_replace('/((?:(?:[^;]+);){3})/',"$1\n",$str);
echo $str2;

As explained in Magnus Eriksson's comment and mine, you just have to use "\n" as first parameter of your implode:
$checkbox = implode("\n", $_POST['product']);
Please notice the use of double quotes (") in order for \n to be used as a linebreak.

Related

Split a single string into an array using specific Regex rules

I'm processing a single string which contains many pairs of data. Each pair is separated by a ; sign. Each pair contains a number and a string, separated by an = sign.
I thought it would be easy to process, but i've found that the string half of the pair can contain the = and ; sign, making simple splitting unreliable.
Here is an example of a problematic string:
123=one; two;45=three=four;6=five;
For this to be processed correctly I need to split it up into an array that looks like this:
'123', 'one; two'
'45', 'three=four'
'6', 'five'
I'm at a bit of dead end so any help is appreciated.
UPDATE:
Thanks to everyone for the help, this is where I am so far:
$input = '123=east; 456=west';
// split matches into array
preg_match_all('~(\d+)=(.*?);(?=\s*(?:\d|$))~', $input, $matches);
$newArray = array();
// extract the relevant data
for ($i = 0; $i < count($matches[2]); $i++) {
$type = $matches[2][$i];
$price = $matches[1][$i];
// add each key-value pair to the new array
$newArray[$i] = array(
'type' => "$type",
'price' => "$price"
);
}
Which outputs
Array
(
[0] => Array
(
[type] => east
[price] => 123
)
)
The second item is missing as it doesn't have a semicolon on the end, i'm not sure how to fix that.
I've now realised that the numeric part of the pair sometimes contains a decimal point, and that the last string pair does not have a semicolon after it. Any hints would be appreciated as i'm not having much luck.
Here is the updated string taking into account the things I missed in my initial question (sorry):
12.30=one; two;45=three=four;600.00=five
You need a look-ahead assertion for this; the look-ahead matches if a ; is followed by a digit or the end of your string:
$s = '12.30=one; two;45=three=four;600.00=five';
preg_match_all('/(\d+(?:.\d+)?)=(.+?)(?=(;\d|$))/', $s, $matches);
print_r(array_combine($matches[1], $matches[2]));
Output:
Array
(
[12.30] => one; two
[45] => three=four
[600.00] => five
)
I think this is the regex you want:
\s*(\d+)\s*=(.*?);(?=\s*(?:\d|$))
The trick is to consider only the semicolon that's followed by a digit as the end of a match. That's what the lookahead at the end is for.
You can see a detailed visualization on www.debuggex.com.
You can use following preg_match_all code to capture that:
$str = '123=one; two;45=three=four;6=five;';
if (preg_match_all('~(\d+)=(.+?);(?=\d|$)~', $str, $arr))
print_r($arr);
Live Demo: http://ideone.com/MG3BaO
$str = '123=one; two;45=three=four;6=five;';
preg_match_all('/(\d+)=([a-zA-z ;=]+)/', $str,$matches);
echo '<pre>';
print_r($matches);
echo '</pre>';
o/p:
Array
(
[0] => Array
(
[0] => 123=one; two;
[1] => 45=three=four;
[2] => 6=five;
)
[1] => Array
(
[0] => 123
[1] => 45
[2] => 6
)
[2] => Array
(
[0] => one; two;
[1] => three=four;
[2] => five;
)
)
then y can combine
echo '<pre>';
print_r(array_combine($matches[1],$matches[2]));
echo '</pre>';
o/p:
Array
(
[123] => one; two;
[45] => three=four;
[6] => five;
)
Try this but this code is written in c#, you can change it into php
string[] res = Regex.Split("123=one; two;45=three=four;6=five;", #";(?=\d)");
--SJ

How to format my data in php

I have an array in php, with print_r it looks like this
Array (
[0] => Array ( [0] => 2 [1] => 3 [2] => 3 [3] => 1 [4] => 1 [5] => 4 [6] => 1 )
[1] => Array ( [0] => 1 [1] => 2 [2] => 2 [3] => 1 [4] => 1 [5] => 1 [6] => 1 )
)
when I do json_encode($mydata) it looks like this
[["2","3","3","1","1","4","1"],["1","2","2","1","1","1","1"]]
but I need this without the quotes, as the next processing simply needs a dataset like this:
var dataset = [ 5, 10, 15, 20, 25 ];
the dataset was never intended to use json standards, I simply need to get my array formatted correctly.
so the question is either "how do I remove quotes from json" which is simply nonstandard invalid json and won't get me the responses I'd need
OR
"how do I format this php array to be like the dataset".
it either involves a different kind of print function in php, or it involves some forloop regex in javascript
You need to use the JSON_NUMERIC_CHECK flag, this will force all numeric strings to be converted to numbers.
Like so:
json_encode($array,JSON_NUMERIC_CHECK);
Please note that this flag is only available from PHP version 5.3.3
Ehhh you could try this:
$d = array();
foreach($myData as $data) {
$d[] = "[" . implode(",", $data) . "]";
}
echo "[" . implode(",", $d) . "]";
Demo: http://codepad.org/nTveAGWm
Although echoing out json_encode($myData); worked as well: http://codepad.org/KTfQHz6s
The reason json_encode is putting quotes is because the data is a string.
Try this example to view the difference:
$arr = array(array(4,5,6), array(8,10, "11"));
print_r($arr);
echo "<br>";
echo json_encode($arr);
You can try to use intval to parse it as int before json_encoding
you could try this
$c = array(1,2,3);
echo "Non-associative array output: ", json_encode($c), "\n";
return this:
Non-associative array output: [1,2,3]
using your example string u can do smth like this
$arr = json_decode('[["2","3","3","1","1","4","1"],["1","2","2","1","1","1","1"]]');
foreach ($arr as &$val)
foreach ($val as &$item)
$item = (int)$item;
var_dump(json_encode($arr));
finally i get
string(33) "[[2,3,3,1,1,4,1],[1,2,2,1,1,1,1]]"

How to get the strings out of this?

I am trying to get some specific values out of the following string:
{"car":"Toyota"{"car":"honda"{"car":"BMW{"car":"Hyundai"
I want to get 'Toyota' out of that. The string is randomly generated, so it could be Benz or Pontiac.
Not really sure what this crazy string is from, but if you've accurately shown the format, this will extract the strings you're after:
$string = '{"car":"Toyota"{"car":"honda"{"car":"BMW{"car":"Hyundai"';
$string = array_filter(
explode(',',
preg_replace(
array('/"/', '/{/', '/:/', '"car"'),
array('', ',', '', ''),
$string
)
)
);
print_r($string);
// Output: Array ( [1] => Toyota [2] => honda [3] => BMW [4] => Hyundai )
... if, instead, this is just a horrible typeo and this is supposed to be JSON, use json_decode:
$string = '[{"car":"Toyota"},{"car":"honda"},{"car":"BMW"},{"car":"Hyundai"}]'; // <-- valid JSON
$data = json_decode($string, true);
print_r($data);
// Output: Array ( [0] => Array ( [car] => Toyota ) [1] => Array ( [car] => honda ) [2] => Array ( [car] => BMW ) [3] => Array ( [car] => Hyundai ) )
Documentation
preg_replace - http://php.net/manual/en/function.preg-replace.php
array_filter - http://php.net/manual/en/function.array-filter.php
explode - http://php.net/manual/en/function.explode.php
json_decode - http://php.net/manual/en/function.json-decode.php
Although this looks like a corrupt piece of JSON, I would say you can get the first car with explode().
$string = '{"car":"Toyota"{"car":"honda"{"car":"BMW{"car":"Hyundai"';
$string = explode("{", $string);
$firstcar = $string[1]; //your string starts with {, so $string[0] would be empty
$firstcar = explode(":", $firstcar);
$caryouarelookingfor = $firstcar[1]; // [0] would be 'car', [1] will be 'Toyota'
echo $caryouarelookingfor // output: "Toyota"
But, as also mentioned in the comments, the string looks like a corrupt piece of JSON, so perhaps you want to fix the construction of this string. :)
EDIT: typo in code, as said in first comment.

php explode something into array, but using values in between

I have a string I want to clean up and put into an array so that I can search through it in mysql.
// Here's one example of what the string might have:
$string1 = "(1) *value1* *value2*; (2) *value3* *value4* *value5*; (3) *value6*";
// And here's another possibility:
$string2 = "*value1* *value2* *value3* *value4*";
// I want to remove all the "(#)" stuff, and explode all the values into an array
// This is what I have so far:
// $string can be like the examples $string1 or $string2
$string_clean = str_replace("* *","",trim(preg_replace("/\((\d)\)/i", "", $string)));
$my_array = explode('*', trim($string_clean, '*'));
However, this is what I'm getting:
Array ( [0] => value1 [1] => [2] => value2 [3] => [4] => value3 [5] => [6] => value4 [7] => [8] => value5 )
I suppose I could just find a function to remove all empty items from the array, but I'm wondering if there's a more effective way to do this?
You need preg_match_all():
preg_match_all('#\*([^*]+)\*#', $string, $matches);
$result = $matches[1];
// $result is array('value1', 'value2', ...)
This will find all *something* and return the strings between the *.

Concatenate the elements in a PHP array

How can I turn the following array below so it looks like example 2 using PHP.
Example 1 array.
Array ( [0] => &sub1=a1 [1] => &sub2=aa [2] => &sub3=glass-and-mosaics [3] => &sub4=guides-and-reviews [4] => &sub5=silent-movies [5] => &sub6=even-more-eastern-religions-and-philosophies )
Example 2.
&sub1=a1&sub2=aa&sub3=glass-and-mosaics&sub4=guides-and-reviews&sub5=silent-movies&sub6=even-more-eastern-religions-and-philosophies
can use implode
You can use the implode function.
$arr = array(0 => '&sub1=a1',1 => '&sub2=aa');
$str = implode('',$arr);
just do a $myVar = implode('', $array);
If this is a query fragment of a URL, use http_build_query instead:
echo http_build_query(
'sub1'=>'a1',
'sub2'=>'aa',
'sub3'=>'glass-and-mosaics',
'sub4'=>'guides-and-reviews',
'sub5'=>'silent-movies',
'sub6'=>'even-more-eastern-religions-and-philosophies'
);

Categories