PHP reading a txt data file and passing data to ar

2019-03-01 01:10发布

问题:

I need to extract the following data from a txt file(displayed in link),then save every field specified on mysql, my problem is how do I get every field contained in a row since its separated by spaces

I tried, array = explode(' ', $line); but that method saves spaces

I would like to pu it into an array ,

Array=(
 [0] => '1',
 [ 1] => 'OC1',
 [2] => 'Columna', 
 [3] => '1',
 [4] => 'IN45X104',
 [5] => '11745'
 ....
 );  

回答1:

$string = preg_replace("/\s[\s]+/",",",$string);
$array = explode(",",$string);

preg_replace just work like str_replace but allow you to replace with using regular expression /\s[\s]+/ matches multiple white spaces and then all that white spaces replace with single "," so its easy to explode now.

Function Source : http://in3.php.net/manual/en/function.preg-replace.php



回答2:

Use preg_split() to match complex delimiters

http://codepad.org/fhsTWsZc

<?php

$line="test test2  test3";
$array=preg_split('/\s+/',$line);
print_r($array);


回答3:

try this,

$tok = strtok($string, " \n\t\x0B\0");
while ($tok !== false) 
{
 echo "Word=$tok<br />";
 $tok = strtok(" \n\t\x0B\0");
}

strtok() splits a string (str) into smaller strings (tokens), with each token being delimited by any character from token. That is, if you have a string like "This is an example string" you could tokenize this string into its individual words by using the space character as the token.