5

Please help me on this.

$str = "col_1          col_2  col_3
row1 row2 row3
row12 row22        row33";

$arr = explode("\n", $str);

foreach($arr as $line)
{
   $temp_arr = explode(WHAT HERE, $line); 
}

How do I explode each line into array?? I want $temp_arr[0] = col_1, $temp_arr[1] = col2, $temp_arr[2] = col_3 next line will have $temp_arr[0] = row1, $temp_arr[1] = row2

You guys are awesome. It works on my example but it doesn't work on my real problem. I export windows xp processes and want to explode them.

Caption              CommandLine                                                                                                                                                                                                                                                                   ProcessId  
System Idle Process                                                                                                                                                                                                                                                                                0          
System                                                                                                                                                                                                                                                                                             4          
smss.exe             \SystemRoot\System32\smss.exe                                                                                                                                                                                                                                                 604        
avgrsx.exe           C:\PROGRA~1\AVG\AVG10\avgrsx.exe /restart /boot                                                                                                                                                                                                                               692        
csrss.exe            C:\WINDOWS\system32\csrss.exe ObjectDirectory=\Windows SharedSection=1024,3072,512 Windows=On SubSystemType=Windows ServerDll=basesrv,1 ServerDll=winsrv:UserServerDllInitialization,3 ServerDll=winsrv:ConServerDllInitialization,2 ProfileControl=Off MaxRequestThreads=16  780        
winlogon.exe         winlogon.exe                                                                                                                                                                                                                                                                  820        
services.exe         C:\WINDOWS\system32\services.exe                                                                                                                                                                                                                                              880        
lsass.exe            C:\WINDOWS\system32\lsass.exe                                                                                                                                                                                                                                                 892        
nvsvc32.exe          C:\WINDOWS\system32\nvsvc32.exe                                                                                                                                                                                                                                               1052       
svchost.exe          C:\WINDOWS\system32\svchost -k DcomLaunch                                                                                                                                                                                                                                     1168       
svchost.exe          C:\WINDOWS\system32\svchost -k rpcss                                                                                                                                                                                                                                          1240       
svchost.exe          C:\WINDOWS\System32\svchost.exe -k netsvcs                                                                                                                                                                                                                                    1328       
svchost.exe          C:\WINDOWS\system32\svchost.exe -k NetworkService                                                                                                                                                                                                                             1404       
svchost.exe          C:\WINDOWS\system32\svchost.exe -k LocalService                                                                                                                                                                                                                               1520       
spoolsv.exe          C:\WINDOWS\system32\spoolsv.exe                                                                                                                                                                                                                                               1664       
explorer.exe         C:\WINDOWS\Explorer.EXE                                                                                                                                                                                                                                                       1956       
jqs.exe              "C:\Program Files\Java\jre6\bin\jqs.exe" -service -config "C:\Program Files\Java\jre6\lib\deploy\jqs\jqs.conf"                                                                                                                                                                460        
avgtray.exe          "C:\Program Files\AVG\AVG10\avgtray.exe"                                                                                                                                                                                                                                      1156       
rundll32.exe         "C:\WINDOWS\system32\RUNDLL32.EXE" C:\WINDOWS\system32\NvMcTray.dll,NvTaskbarInit                                                                                                                                                                                             1204       
alg.exe              C:\WINDOWS\System32\alg.exe                                                                                                                                                                                                                                                   1376       
AVGIDSMonitor.exe    "C:\Program Files\AVG\AVG10\Identity Protection\agent\bin\avgidsmonitor.exe"                                                                                                                                                                                                  660        
iexplore.exe         "C:\Program Files\Internet Explorer\iexplore.exe"                                                                                                                                                                                                                             620        
OUTLOOK.EXE          "C:\Program Files\Microsoft Office\Office12\OUTLOOK.EXE"  /recycle                                                                                                                                                                                                            1884       
SQLyog.exe           "C:\Program Files\SQLyog\SQLyog.exe"                                                                                                                                                                                                                                          2596       
UniKeyNT.exe         "C:\Program Files\unikey40RC2-1101-win32\UniKeyNT.exe"                                                                                                                                                                                                                        964        
avgcsrvx.exe         C:\Program Files\AVG\AVG10\avgcsrvx.exe /pipeName=4f758821-d931-4842-ae08-b81fe89b843a /coreSdkOptions=0 /binaryPath="C:\Program Files\AVG\AVG10\" /registryPath="SYSTEM\CurrentControlSet\Services\Avg\Avg10"                                                                3788       
svchost.exe          C:\WINDOWS\system32\svchost.exe -k imgsvc                                                                                                                                                                                                                                     3604       
mstsc.exe            "C:\WINDOWS\system32\mstsc.exe"                                                                                                                                                                                                                                               3868       
notepad++.exe        "C:\Program Files\Notepad++\notepad++.exe"                                                                                                                                                                                                                                    4072       
notepad.exe          "C:\WINDOWS\system32\NOTEPAD.EXE" C:\Documents and Settings\Quy Nguyen\Desktop\cool.txt                                                                                                                                                                                       2228       
cmd.exe              "C:\WINDOWS\system32\cmd.exe"                                                                                                                                                                                                                                                 2552       
wmic.exe             WMIC /OUTPUT:C:\ProcessList.txt PROCESS get Caption,Commandline,Processid                                                                                                                                                                                                     2480       
wmiprvse.exe         C:\WINDOWS\system32\wbem\wmiprvse.exe                                                                                                                                                                                                                                         1744       
3
  • Use ctrl-K or the {} button in the editor for code blocks. Backticks are for simple single-line snippets or in-line citations. Commented Jun 28, 2011 at 21:13
  • duplicated i believe somewhere Commented Jun 28, 2011 at 21:14
  • I have edited my answer to reflect a solution to the problem as you have now posted it. Enjoy =) Commented Jun 28, 2011 at 21:48

4 Answers 4

3

replace

$temp_arr = explode(WHAT HERE, $line);

with

$temp_arr = preg_split('/\s+/', $line, -1, PREG_SPLIT_NO_EMPTY);

Edit: added PREG_SPLIT_NO_EMPTY

OK, so your question changed a bit. This code should do exactly what you want:

$processes = 'the list you posted';

$temp = preg_split('/\s*(?:\r?\n)+/', $processes, -1, PREG_SPLIT_NO_EMPTY);
$process_list = array();
foreach ($temp as $process) {
    $process_list[] = array_pad( // array_pad makes the length consistent
        preg_split(
            '/\s{2,}/', // match only 2 or more consecutive spaces for splitting
            $process,
            3,
            PREG_SPLIT_NO_EMPTY), // ignore empty matches (i.e., end of line)
        3, // pad array to a length of 3
        ''
    );
}

$process_list_final = array();
$process_list_titles = array_shift($process_list);

foreach ($process_list as &$plist_item) {
    $plist_item = array_combine($process_list_titles, $plist_item);
}

It probably needs a bit of cleanup, but you can do that on your own =)

Some functions for you to look up:

Sign up to request clarification or add additional context in comments.

4 Comments

the PREG_SPLIT_NO_EMPTY will keep you from getting an empty element at the end of the arrays.
The docs. say If this flag is set, only non-empty pieces will be returned by preg_split().
@cwallenpoole: I don't see how what you said and what I said don't match =) I'm referring to this specific example, of course.
Note also: it wouldn't be terribly difficult to change this code so that it only goes through one loop, but you'd have to get the titles out beforehand. This is mildly less generic, although arguably more efficient from an execution standpoint. "This is left as an exercise to the rea^H^H^H asker."
2

You probably want preg_split.

$str = "col_1          col_2  col_3
    row1 row2 row3
    row12 row22        row33";

$arr = explode("\n", $str);

foreach($arr as $line)
{
   $temp_arr = preg_split("#\s+#", $line, -1, PREG_SPLIT_NO_EMPTY); 
}

preg_split, unlike explode, allows you to use something called regular expressions to split a string into chunks. In this case:

  • # "Begin the regex"
  • \s+ means "one or more consecutive whitespaces".
  • -1 means there should not be any limit to the number of matches (change this to your preferred number if you'd like)
  • PREG_SPLIT_NO_EMPTY is a special constant which tells the method to never return an empty result so you don't need to worry about this:

        row1

EDIT


Just noticed your edit. You can modify the regular expression to "#\s++#" to make it search for at least 2 spaces, and you can keep adding +'s, or you can use braces to do the job for you. You can see more here.

1 Comment

+1 because your answer has a lot more detail than mine does =)
0
$temp_arr = explode("\n", $line); 

Comments

0

In PHP you can do that very differently in php.

I dont know what the real data you have to explode, but if you have just space-delimited data you can do just that:

foreach ($arr as $line) {
  // removing double-spaces
  while(strpos($line, ' ') !== false) $line = str_replace('  ', ' ', $line);
  // trim leading and trailing spaces. you can safely move it to explode
  $line = trim($line);
  // will be better if you replace double-spaces before. it will be faster a lot.
  //-> just space character (0x20) here now (!)
  $temp_arr = explode(' ', $line);
}

Also you can split array to variables instantly with list. Just like that:

list( $row1, $row2, $lastrow ) = explode(" ", $line);`

Don't use preg_split for that simple problem. Too slowly for that.

Good luck)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.