regex - extracting multiple fields from a text file using php -


What's the best way to extract multiple (~ 40 values) from a text file using PHP?

The data is more or less like:

  NAMEA valuea NAMEB valueb  

I find this data in a proper * Looking for the approach - structure, because I must specify regexs for all of them (all 40).

Did I make myself clear?

* Meaning, the default / painful method will be for me:

  $ namea = extractfunction ("regexa", $ textfilevalue); $ Nameb = extract function ("regeb", $ textfilevalue);  

... 40 times!


These rows can not be in the same order, or may exist in each file. Every name, such as the text is: "Registration number:", or "applicant's name:" (i.e., with the vacancy in the name that I was calling as NAMEA)


Response.

I'm looking for a sensible "path" to write my code, so its readable, modified, makes an object / array easy to callable, etc. ... "Good coding style!" :)


@adam - they actually do ... and also slash together ...


@ Alex - amazing amazing man! that was nice! Can you "sort" the rsultant array by removing everything from "key_x" and beyond, any insight on this? Should I open it as a new question?

Here's my take:

somefile.txt:

  NAMEA value NAMEB valueb  

PHP code:

  $ File = file_get_contents ('./filefile.txt'); $ String = preg_replace ('~ ^ (. +?) \ S + (. +?) $ ~ M', '$ 1 = $ 2', $ file); $ String = str_replace (array ("\ r \ n", "\ r", "\ n"), '& amp;', $ string); $ Result = array (); Parse_str ($ string, $ result); Echo '& lt; Pre & gt; '; Print_r ($ result); Echo & lt; / Pre & gt; '; Array ([NAMEA] = & gt; value [[NAMEB] = & gt; valueb)  

Output:

  >  

You may also be able to make it easy on PHP 5.3 +.


Edit : My last version fails for Keys @ Spaces like call pellets have seen I have not read the question with enough attention. It's possible that since you always think the : is using the embedded key:

preg_replace ('~ ^ (? +? ): \ S + (. +?) $ ~ M ',' $ 1 = $ 2 ', $ file);

To remove everything from the key_x at the end of the file, you can do something like this:

  $ string = substr ($ String, 0, stropo ($ string, 'key_x'));  

The whole thing will look like this:

somefile.txt:

  Registration number: Value Applicant's Name: valueb  

PHP Code:

  $ file = file_get_contents ('. / Somefile.txt') ; $ String = substr ($ file, 0, stropo ($ file, 'key_x')); $ String = preg_replace ('~ ^ (. +?): \ S + (. +?) $ ~ M', '$ 1 = $ 2', $ string); $ String = str_replace (array ("\ r \ n", "\ r", "\ n"), '& amp;', $ string); $ Result = array (); Parse_str ($ string, $ result); Echo '& lt; Pre & gt; '; Print_r ($ result); Echo & lt; / Pre & gt; '; Aare ([registration_number] = & gt; value [applicant_name] => human)  

Output:

 > 

Comments