Ok, ive imported contents of .txt file into array, and im having problems with removing some parts of the string in array. This is the sample output of the array:
[55] => 28649706-20440929 73,66 02 [57] => 28613238-20600568 255,56 03 [59] => 40595693002 777,16 04 [79] => 078-50-4327086 691,24 02
I would like to:
If string has only one hyphen, like in [55] and [57], delete first part of the string together with hyphen,
If string has 2 hyphens, like in [79], leave it as it is,
- Remove last 2 numbers in all array elements,
- I would like to export it in .csv file with each part of the string in its own column, suppose i need delimiter between, or i need to split those strings in its own subarray ?
So far, i’ve able to solve issue no. 3, delete last 2 characters from array elements:
$content = file_get_contents($_FILES['file']['tmp_name']); $output = explode("n", $content); foreach ($output as $key => $index) { $string = preg_replace('/X{3}z/u', '', $output); }
Still, im having issues with removing parts of the string with 2 hyphens, and outputting it in .csv in separate columns.
Thank you.
EDIT:
i’ve managed to create downloadable file, but data isnt structured as expected, they are all placed in first row, and i would like to place it in each separate column:
header('Content-Encoding: UTF-8'); header('Content-Type: text/csv; charset=utf-8' ); header(sprintf('Content-Disposition: attachment; filename='.$_FILES['file']['name'].'-%s.csv', date( 'dmY-His' ))); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); ob_end_clean(); $fp = fopen("php://output", 'w'); fputcsv($fp, $string); fclose($fp); die();
Advertisement
Answer
I suggest
$string = preg_replace('~^s*(?:d+-(?=d[^-]*$))?|s+d+s*$~', '', $output);
See the regex demo
Details
^
– start of strings*
– 0+ whitespaces(?:d+-(?=d[^-]*$))?
– an optional sequence ofd+
– 1+ digits-
– a hyphen(?=d[^-]*$)
– a positive lookahead that requires a digit and then any 0+ chars other than-
till the end of the string
|
– ors+
– 1+ whitespacesd+
– 1+ digitss*
– 0+ whitespaces$
– end of string.