Hallo Experten!
Ich bin erstens neu hier und zweitens ein PHP- Anfänger.
Um ein Sortierproblem zu lösen, habe ich mal einen PHP- Script für die Kommandozeile zusammengebastelt. Der macht alles ganz gut, doch möchte ich eure Kritik dazu.
Dann hätte ich noch ein paar Fragen:
1. Wenn in der Ausführung ein Fehler auftritt, wie kann ich an die Kommandozeile einen Error- Wert zurückgeben?
2. Eigentlich könnte man bei fast jeder Funktion eine Erfolgsprüfung machen und gegebenenfalls eine Fehlermeldung ausgeben. In den Beispielen, die ich gefunden habe, ist das nicht der Fall, so habe ich das auch mal weggelassen. Was meint ihr dazu?
3. Ziel ist schlussendlich eine kompilierte Version, d.h. dass ich ein Kommandozeilen- Tool habe. Könnt ihr mir da etwas empfehlen?
Hintergrund: Ich muss in einem CAD mittels 'User Functions' eine Liste nach 'natural order' sortieren. Die eingebaute Sortierfunktion unterstützt 'natural sort' nicht und selber machen ist mir zu aufwändig (habe es probiert). Als externe Lösung könnte ich auf der Kommandozeile die Sortierung durchführen lassen. Ein fertiges Programm habe ich nicht ergooglen können, also dann per PHP...
Programmcode:
PHP-Code:
#!/usr/bin/php
<?php
// NatSort.php - A simple program to sort text files in the so called 'natural order'
// ===========
//
// This code must be compiled to an executable file, then the CLI syntax would be:
// NatSort.exe
// The program looks for an input file called 'InFile.txt' then it will write a
// sorted file 'OutFile.txt'.
//
// Programmer: Rüeblibär
//
// Release 1.00: 2006-08-10 Final release
//
// Run this in a PHP environement: php NatSort.php
//
if($argc > 1) // Command line arguments are accessible with $argc and $argv
{
echo "\nNatSort.exe - A program to sort a text file in the natural order";
echo "\n-----------\n\n";
echo "Syntax: NatSort.exe - or\n";
echo " NatSort.exe -h (-? or -help)\n\n";
echo "The program looks for an input file 'InFile.txt' then it writes\n";
echo "a sorted output file 'OutFile.txt'.\n\n";
echo "The option '-h' leads to this text\n\n";
echo "Version 1.00 / 2006-08-10 / Rüeblibär\n\n";
}
else
{
$InFile = "InFile.txt";
$OutFile = "OutFile.txt";
if(file_exists($InFile))
{
$Array = file($InFile); // Load file in array
natsort($Array); // Sort array
$FilePointer = fopen($OutFile, "w"); // Open text file
flock($FilePointer, LOCK_EX); // Locks the file for others
fseek($FilePointer, 0, SEEK_SET); // Set file pointer to the begin of file
ftruncate($FilePointer, 0); // Deletes old contents
fseek($FilePointer, 0, SEEK_SET); // Again to the begin of file
foreach ($Array as $Line)
{
fputs($FilePointer, $Line); // Write array in file (line for line)
}
flock($FilePointer, LOCK_UN); // Unlocks the file
fclose($FilePointer); // Close the text file
echo "\nOK\n";
}
else
{
echo "\nFile Error: 'InFile.txt' not found\n";
}
}
?>