Karl Herrick

A technologist and web developer | Posts about technology encountered along the journey.

PHP one-liners on the CLI

PHP CodeAfter checking out a page called Perl one-liners and reading how you could execute Perl inline on the CLI, I decided to try and replicate some grep functionality using PHP one-liners for fun.

Interestingly, PHP seems quite slow compared to other tools for my particular task, so I probably won’t be using these approaches outlined below in daily practice. 🙂

Here are some stats for a search through all files in the current directory for words with ‘foo’ in them:

time to search using PHP:

username@host:~$ time php -r '$s="foo";$fs=scandir(".");foreach($fs as $f){$ls=file($f);foreach($ls as $l){if(strpos($l,$s)!==false)echo "$f:$l";}}'
filename.txt:football season is approaching

real	0m0.013s
user	0m0.012s
sys	0m0.000s

time to search using Perl:

username@host:~$ time perl -ne 'print "$ARGV:$_" if /foo/' *
filename.txt:football season is approaching

real	0m0.003s
user	0m0.000s
sys	0m0.000s

time to search using grep:

username@host:~$ time grep -H foo *
filename.txt:football season is approaching

real	0m0.002s
user	0m0.000s
sys	0m0.000s

A you can see, to use the one liner technique it appears to be as simple as “compressing” your scripts down to a single line, making sure they are shell friendly, and executing them with the “-r” option. Some other ones that I worked out with PHP are below:

to search for ‘foo’ and print matching lines in a single file:

php -r '$s="foo";$ls=file("filename");foreach($ls as $l){if(strpos($l,$s)!==false)echo$l;}'

to search for ‘foo’ and print matching lines in all files in the current directory:

php -r '$s="foo";$fs=scandir(".");foreach($fs as $f){$ls=file($f);foreach($ls as $l){if(strpos($l,$s)!==false)echo$l;}}'

to search for ‘foo’ and print matching lines recursively from the current directory:

php -r '$s="foo";$t=new RecursiveDirectoryIterator(".");foreach(new RecursiveIteratorIterator($t) as $f){$ls=file($f);foreach($ls as $l){if(strpos($l,$s)!==false)echo$l;}}'