2

I am trying to separating data from Isam files looping it line by line using fgets and with substr to get correct data from correct position of line.

Source data:

000000124325424Productname    Type    Price    Weight    Unit    Unitcode
000000124325324Productname2   Type2   Price2   Weight2   Unit2   Unitcode2

Problem is that substr does not recocnize those extra spaces between data and therefore position of data is changing every line.

Substr is "seeing" line like this:

000000124325424Productname Type Price Weight Unit Unitcode

Is there any way to preserve the spaces between items?

davidkonrad
  • 83,997
  • 17
  • 205
  • 265
Roger Wayne
  • 419
  • 3
  • 20

2 Answers2

2

After editing the question it hits me that you perhaps are dealing with a tab delimited string \t. Either way, sanitize each string before whatever you are trying to do with substr() :

$s = preg_replace('/\s+/', ' ', $s);

This will strip out multiple blanks " "=>" ", tabs \t and even line breaks.


Perhaps you can find explode() as a better approach after sanitizing :

explode(" ", str_replace("\t", " ", $line1))[0] 

will always be first item, i.e product code without extra spaces.

davidkonrad
  • 83,997
  • 17
  • 205
  • 265
  • That's correct, not spaces but tabs. preg_replace('/\s+/', ' ', $s) didn't work but replacing only tabs ($line = str_replace("\t", " ", $line1);) did the trick. Thanks anyway! – Roger Wayne Oct 03 '15 at 17:34
  • @RogerWayne - Weird, `/\s+/` works for me. See update, perhaps you dont need `substr` after all, if all your lines has the same structure. Just a suggestion. Thank you for accepting the answer. – davidkonrad Oct 03 '15 at 17:43
1

When you display text in a web page, the web browser doesn't show multiple spaces as such. Try wrapping your text in a preformatting tag, like so

<pre>000000124325324Productname2   Type2   Price2   Weight2   Unit2   Unitcode2</pre>

Then the browser will render it with all the spaces shown.

You can troubleshoot this kind of problem using View Source... In your browser.

O. Jones
  • 103,626
  • 17
  • 118
  • 172