Sie sind auf Seite 1von 11

Perl Reference Card Cheat Sheet

by Nikolay Mishin (mishin) via cheatography.com/1008/cs/399/

About 1.1 Scalars and Strings (cont) 1.2 Arrays and Lists (cont)

This is version 2 of the perl reference card. e(E) scientific notation revers​e(@a); reverse @a
(cl) 2008 Michael Goerz <go​erz​@ph​ysi​k.f​u- f decimal floating point @a = sort{$ela <=> sort numeri​cally
b​erl​in.d​e>.
$elb}(@a);
g, G shorter %e or %f /
http:/​/ww​w.p​hys​ik.f​u-​ber​lin.de​/~g​oerz/
%E or %f @a = split(​/-/​,$s); split string into @a
Inform​ation taken liberally from the perl
docume​ntation and various other sources. o signed octal $s = join(“, ” @c); join @a elements
You may freely distribute this document. into string
s string of chars
@a2 = @a[1,2​,6..9]; array slice
u, x, X unsigned decimal int /
1 Variable Types
hex int / hex int in @a2 = grep(!​/^#/, @a); remove comments
caps from @a
1.1 Scalars and Strings
p address pointer
Perl image
chomp(​$str); discard trailing \n n nothing printed
$v = chop($​str); $v becomes trailing modifiers: h,l,L arg is short int / long
char int, double/ long

eq, ne, lt, gt, le, ge, string comparison double

cmp More:

$str = “0” x 4; $str is now “0000” chr, crypt, hex, lc, q/STRING/,
$v = index(​$str, $x); find index of $x in $str, lcfirst, length, oct, ord, qq/STR​ING/, reverse,
pack uc, ucfirst
$v = rindex​($str, $x); starting from left or right

$v = substr​($str, extract substring 1.2 Arrays and Lists


$strt, $len);
@a = (1..5); array initia​liz​ation
$cnt = $sky =~ tr/0- count the digits in $sky
9//; $i = @a; number of elements in
@a
$str =~ tr/a-zA-Z/ change non-alphas to
/cs; space ($a, $b) = ($b, swap $a and $b
1.3 Hashes
$a);
$v = sprint​f(“%10s format string
%08d”,​$s,$n); $x = $a[1]; access to index 1 %h=(k1 => “val1”,k2 hash initia​liz​ation
=> 3);
Format String: %[flag​s][​0] $i = $#a; last index in @a
[​wid​th]​[.p​rec​isi​on]​[mo​d]ty $val = $map{k1}; recall value
push(@a, $s); appends $s to @a
pe @a = %h; array of keys and
$a = pop(@a); removes last element
types: values
chop(@a); remove last char (per el.)
%h = @a; create hash from array
c character
$a = shift(@a); removes first element
foreach $k iterate over list of keys
d(i) signed decimal int
(keys(​%h)​){..}

foreach $v iterate over list of


(vals(​%h)​){..} values

while (($k,$​v)=each iterate over key-


%h){..} va​lue​-pairs

delete $h{k1}; delete key

exists $h{k1} does key exist?

defined $h{k1} is key defined?

By Nikolay Mishin (mishin) Published 2nd June, 2012. Sponsored by CrosswordCheats.com


cheatography.com/mishin/ Last updated 5th June, 2014. Learn to solve cryptic crosswords!
mishin.narod.ru Page 1 of 6. http://crosswordcheats.com
Perl Reference Card Cheat Sheet
by Nikolay Mishin (mishin) via cheatography.com/1008/cs/399/

3 References and Data Structures 3 References and Data Structures (cont) 2 Basic Syntax (cont)

$aref = \@a; reference to sub createcnt{ my $c=shift; closure, $c eval {$a=$a/$b; }; warn $@ exception
array return sub { print "​$c+​+"; }; } persists if $@; handling

$aref = [1,"​foo​"​,un​def​,13]; anonymous array *foo{T​HING} foo-syntax for


creating refs 6 Regular Expres​sions
$el = $aref-​>[0]; $el = access element
@{$are​f}[0]; of array ($var =~ /re/), matches / does not match
Link to perl cheat ($var !~ /re/)
$aref2 = [@{$ar​ef1}]; copy array

$href = \%h; reference to perlcheat m/patt​ern​/ig​msox matching pattern

hash http:/​/ww​w.c​hea​tog​rap​hy.c​om​/mi​shi​n/c​hea​t- c

$href ={APR => 4,AUG => anonymous hash s​hee​ts/​per​lcheat/ qr/pat​ter​n/imsox store regex in variable

8}; perl-r​efe​ren​ce-card s/patt​ern​/re​pla​ce search and replace

$el = $href-​>{APR}; $el = access element m​ent​/ig​msoxe


http:/​/ww​w.c​hea​tog​rap​hy.c​om​/mi​shi​n/c​hea​t-
%{$hre​f}{​APR}; of hash s​hee​ts/​per​l-r​efe​ren​ce-​card/ Modi​fie​rs:

$href2 = {%{$hr​ef1}}; copy hash i case- o compile once


20-kil​ler​-pe​rl-​pro​gra​mmi​ng-tips
if (ref($r) eq "​HAS​H") {} checks if $r i​nse​nsitive
http:/​/ww​w.c​hea​tog​rap​hy.c​om​/mi​shi​n/c​hea​t-
points to hash g global x extended
s​hee​ts/​20-​kil​ler​-pe​rl-​pro​gra​mmi​ng-​tip​s-
@a = ([1, 2],[3, 4]); 2-dim array f​or-​beg​inners/ s as single line (. e evaluate replac​ement
$i = $a[0][1]; access 2-dim matches \n)
array 2 Basic Syntax Synt​ax:
%HoA=(​fs=​>["f​"​,"b"], sp=> hash of arrays ($a, $b) = read command line \ escape
["h​"​,"m"]); shift(​@ARGV); params . any single char
$name = $HoA{s​p}[1]; access to hash sub p{my $var = define subroutine ^ start of line
of arrays shift; ...}
$ end of line
$fh = *STDIN globref p(“bla”); execute subroutine
,? 0 or more times (greedy /
$coderef = \&fnc; code ref (e.g.
if(expr){} elsif {} condit​ional nongreedy)
callback)
else {}
+, +? 1 or more times (greedy /
$coderef =sub{print "​bla​"}; anon subroutine unless (expr){} negative condit​ional nongreedy)
&$​cod​eref(); calling anon while (expr){} while-loop ?, ?? 0 or 1 times (greedy /
subroutine
until (expr){} until-loop nongreedy)

do {} until (expr) postcheck until-loop \b, \B word boundary ( \w - \W) /


match except at w.b.
for($i=1; $i<=10; for-loop
$i++){} \A string start (with /m)

foreach $i (@list){} foreac​h-loop \Z string end (before \n)

last, next, redo end loop, skip to next, \z absolute string end
jump to top

By Nikolay Mishin (mishin) Published 2nd June, 2012. Sponsored by CrosswordCheats.com


cheatography.com/mishin/ Last updated 5th June, 2014. Learn to solve cryptic crosswords!
mishin.narod.ru Page 2 of 6. http://crosswordcheats.com
Perl Reference Card Cheat Sheet
by Nikolay Mishin (mishin) via cheatography.com/1008/cs/399/

6 Regular Expres​sions (cont) 6 Regular Expres​sions (cont) 6 Regular Expres​sions (cont)

\G continue from previous \w, \W word char [a-zA-​Z0-9_] / non-word (?<​=..), (? positive / negative look-b​ehind
m//g char <!..)

[...] character set \s, \S whitepace [ \t\n\r\f] / non-space (?>...) prohibit backtr​acking

(...) group, capture to $1, $2 \C match a byte (?{ code embedded code

(?:...) group without capturing \pP, \PP match p-named unicode / non- })

p-​nam​ed-​unicode (??{ code dynamic regex


{n,m} , {n,m}? at least n times, at most
})
m times \p{...}, match long-named unicode / non-

{n,} , {n,}? at least n times \P{...} na​med​-un​icode (? condition corres​ponding to

\X match extended unicode (con​d)y​es| captured parent​heses


{n} , {n}? exactly n times
no)
Posix:
| or
(? condition corres​ponding to look-
\1, \2 text from nth group ($1, [:alnum:] alphan​umeric
(con​d)yes) a​round
...) [:alpha:] alphabetic Vari​ables
Escape Sequen​ces: [:ascii:] any ASCII char
$& entire matched string
\a alarm (beep) \e escape [:blank:] whitespace [ \t]
$` everything prior to matched string
\f formfeed \n newline [:cntrl:] control characters
$' everything after matched string
\r carriage return \t tab [:digit:] digits
$1, $2 ... n-th captured expression
\cx control-x \l lowercase next char [:graph:] alphanum + punctu​ation
$+ last parent​hesis pattern match
\L lowercase until \E \U uppercase until \E [:lower:] lowercase chars
$^N most recently closed capt.
\Q diable metachars \E end case [:print:] alphanum, punct, space
$^R result of last (?{...})
until \E modifi​cations [:punct:] punctu​ation
@-, @+ offsets of starts / ends of groups
Char​acter Classes: [:space:] whitespace [\s\ck]
http:/​/pe​rld​oc.p​er​l.o​rg/​per​lre​qui​ck.html
[amy] 'a', 'm', or 'y' [:upper:] uppercase chars
http:/​/ha​bra​hab​r.r​u/p​ost​/17126/
[f-j.-] range f-j, dot, and dash [:word:] alphanum + '_'
[^f-j] everything except range [:xdigit:] hex digit
f-j
[:^digit:] non-digit
\d, \D digit [0-9] / non-digit
Extended Constr​ucts

(?#text) comment

(?imxs​- enable or disable option


im​sx:...)

(?=...), positive / negative look-ahead


(?!...)

By Nikolay Mishin (mishin) Published 2nd June, 2012. Sponsored by CrosswordCheats.com


cheatography.com/mishin/ Last updated 5th June, 2014. Learn to solve cryptic crosswords!
mishin.narod.ru Page 3 of 6. http://crosswordcheats.com
Perl Reference Card Cheat Sheet
by Nikolay Mishin (mishin) via cheatography.com/1008/cs/399/

Debugging regexp 4 System Intera​ction (cont) 5 Input/​Output (cont)

use re 'taint'; File Tests: open(P​RC,​"​caesar <$file read from


# Contents of $match are tainted if $dirty was |"); process
-r, -w readable, writeable
also tainted.
open(E​XTRACT, "​|sort write to process
-x executable
($match) = ($dirty =~ /^(.*)​$/s);
>Tm​p$$​");
# Allow code interp​ola​tion: -e exists
$line = <IN​FIL​E>; get next line
use re 'eval';
-f, -d, -l is file, directory,
$pat = '(?{ $var = 1 })'; # embedded code @lines = <IN​FIL​E>; slurp infile
symlink
execution foreach $line loop of lines from
-T, -B text file, binary file
/alpha​${p​at}​omega/; # won't fail unless under -T (<S​TDI​N>)​{...} STDIN
# and $pat is tainted -M, -A mod/access age in
print STDERR "​Warning print to STDERR
use re 'debug'; # like "perl -Dr" days
1.\n";
/^(.*)$/s; # output debugging info during @stats = 13-element list with
# compile time and run time close INFILE; close filehandle
stat(“​fil​ena​me”); status
use re 'debug​color'; # same as 'debug', More:
File Tests in Perl http:/​/ww​w.d​evs​hed.co​
# but with colored output
m/c​/a/​Per​l/F​ile​-Te​sts​- binmode, dbmopen, select, syscall,
in​-Perl/ dbmclose, fileno, flock, sysreed, sysseek,
4 System Intera​ction
format, getc, read, readdir, tell,
More:
system​(“cat $f|sort - system call readline, rewinddir, seek, telldi​r,t​run​cate,
chmod, chown, opendir, readlink,
u>​$f.s”); seekdir pack, unpack,
chroot, fcntl, glob, rename, rmdir,
vec
@a = readpi​pe(​“ls​mod”); catch output ioctl, link, lstat, mkdir, symlink, umask, utime
$today = “Today: “.date; catch output
7 Object​-Or​iented Perl and Modules
5 Input/​Output
better: use IPC::Open3 'open3';!
Defining a new class:
chroot​(“/​hom​e/u​ser/”); change root open(I​NFI​LE,​"​in.t​xt​") or open file for input
package Person;
die;
while (<*.c>) {} operate on all c- use strict;
files open(I​NFI​LE,​"​<:u​tf8​"​,"fi​l open file with my $Census;
e"); encoding sub new { #const​ructor, any name is fine
unlink​(“/​tmp​/fi​le”); delete file
open(TMP, "​+>", open anonymous my $class = shift;
if (-f “file.t​xt​”){...} file test my $self = {};
undef); temp file
$self-​>{NAME} = undef; # field
open(M​EMO​RY,​'>', open in-mem​ory​-file
$self-​>{"_​CEN​SUS​"} = \$Census; # class data
\$var);
++ ${ $self-​>{"_​CEN​SUS​"} };
open(O​UT,​"​>ou​t.t​xt") or open output file bless ($self, $class);
die; return $self;
open(L​OG,​"​>>m​y.l​og") open file for append }
or die; sub name { #method
my $self = shift;

By Nikolay Mishin (mishin) Published 2nd June, 2012. Sponsored by CrosswordCheats.com


cheatography.com/mishin/ Last updated 5th June, 2014. Learn to solve cryptic crosswords!
mishin.narod.ru Page 4 of 6. http://crosswordcheats.com
Perl Reference Card Cheat Sheet
by Nikolay Mishin (mishin) via cheatography.com/1008/cs/399/

7 Object​-Or​iented Perl and Modules (cont) 8 One-Liners (cont) 8 One-Liners (cont)

if (@_) { $self-​>{NAME} = shift } -p same as -n, but will also print the -l enables automatic line-e​nding
return $self-​>{N​AME}; contents of $_ processing in the output. Print
} statements will have the new line
Intera​ctive perl -de1;use Term::​Rea​dKey;
sub DESTROY { #destr​uctor separator (\n) added at the end of
Mode:
my $self = shift; -- ${$sel​f->​{"_C​ENS​US"} };} each line.
http:/​/sz​abg​ab.c​om​/us​ing​-th​e-
1; # so the ‘require’ or ‘use’ succeeds
b​uil​t-i​n-d​ebu​gge​r-o​f-p​erl​-as​- -w prints any warning messages.
Using the class:
re​pl.html -e indicates that the following string
use Person;
is to be interp​reted as a perl
$him = Person​->n​ew(); perl- http:/​/ww​w.t​heg​eek​stu​ff.c​om​/20​10/​05
script (i.e., sequence of
$him->​nam​e("J​aso​n"); d​ebugger /​per​l-d​ebu​gger/
commands).
printf "​There's someone named %s.\n", $him- The Perl http:/​/do​cst​ore.mi​k.u​a/o​rel​ly/​per​l/p​ro
>​name; Debugger g​3/c​h20​_01.htm http:/​/pe​rld​oc.p​er​l.o​rg/​per​lru​n.html
use Data::​Dumper; print Dumper​($him); # Perl flags - perl -e '$x = "​Hello world!​n"; print
-T enables taint checking, which
debug pe, -pi, -p, $x;'
instructs perl to keep track of data
http:/​/ww​w.c​ode​pro​jec​t.c​om/​Art​icl​es/​315​2/P​erl​- -w, -d, -i, -
from the user and avoid doing
Ob​jec​t-O​rie​nte​d-P​rog​ramming t? perldoc
anything insecure with it. Here this
http:/​/yn​onp​ere​k.c​om/​cou​rse​/pe​rl/​oo.html perlrun
option is used to avoid taking the
current directory name from the perl -MO=De​parse -p -e 1
Installing Modules:
@INC variable and listing the
perl -MO=De​parse -p -i -e 1
perl -MCPAN -e shell; available .pm files from the
perl -MO=De​parse -p -i.bak -e 1
directory recurs​ively.
https:​//t​wit​ter.co​m/#​!/p​erl​one​liner
8 One-Liners

- (zero) specify the input record separator Examples:


0
1. just lines 15 to 17, effici​ently
- split data into an array named @F
a perl -ne 'print if $. >= 15; exit if $. >= 17;'

- specify pattern for -a to use when splitting 2. just lines NOT between line 10 and 20
F perl -ne 'print unless 10 .. 20'
-i edit files in place

- run through all the @ARGV arguments as


n files, using <>

By Nikolay Mishin (mishin) Published 2nd June, 2012. Sponsored by CrosswordCheats.com


cheatography.com/mishin/ Last updated 5th June, 2014. Learn to solve cryptic crosswords!
mishin.narod.ru Page 5 of 6. http://crosswordcheats.com
Perl Reference Card Cheat Sheet
by Nikolay Mishin (mishin) via cheatography.com/1008/cs/399/

Examples: (cont) Examples: (cont)

3. lines between START and END 14. If you had installed any modules from
CPAN, then you will need to re-install all of
perl -ne 'print if /START$/ .. / END$/'
them. (Naveed Massjouni)
4. in-place edit of *.c files changing all foo to
perl -E 'say for grep /site_​per​l/,​@INC'| xargs
bar
find | perl -Fsite​_perl/ -lane 'print $F[1] if
perl -pi.bak -e 's/\bf​oo​\b/b​ar/g' *.c /\.pm$/' | cpanm --rein​stall

5. delete first 10 lines 15. Give executable rights to all perl file in dir
perl -i.old -ne 'print unless 1 .. 10' foo.txt find /home/​cli​ent​0/p​ubl​ic_html -type f -name
'*.pl' -print0 | xargs -0 chmod 0755
6. change all the isolated oldvar occurr​ences to
newvar 16. Find files matching name-p​attern
perl -i.old -pe 's{\bo​ldv​ar​\b}{​new​var}g' *.[chy] https:​//g​ist.gi​thu​b.c​om/​563679

perl -MFile​::Find -le 'find(​sub​{print


7. printing each line in reverse order
$File:​:Fi​nd:​:name if /\b[a-​z]{​2}_​[A-​Z]
perl -e 'print reverse <>' file1 file2 file3 ....
{​2}/​},"/​usr​")'
8. find palind​romes in the /usr/d​ict​/words
dictionary file

perl -lne '$_ = lc $_; print if $_ eq reverse'


/usr/d​ict​/words

9. comman​d-line that reverses all the bytes in a


file

perl -0777e 'print scalar reverse <>' f1 f2 f3

10. word wrap between 50 and 72 chars

perl -p000e 'tr/ \t\n\r/ /; s/(.


{5​0,7​2})​\s/​$1​\n/g​;$_.="​\n"x2'

11. strip and remove double spaces

perl -pe '$_ = " $_ "; tr/ \t/ /s; $_ =


substr​($_​,1,-1)'

12. move '.txt.out' to '.out'

perl -e '($n = $_) =~ s/\.tx​t(\.ou​t)$/$1/ and


not -e $n and rename $_, $n for @ARGV' *

13. write a hash slice, which we have come as


a reference to a hash

perl -E'my $h={1..8}; say for @{$h}{​1,3​,5,7}'

By Nikolay Mishin (mishin) Published 2nd June, 2012. Sponsored by CrosswordCheats.com


cheatography.com/mishin/ Last updated 5th June, 2014. Learn to solve cryptic crosswords!
mishin.narod.ru Page 6 of 6. http://crosswordcheats.com
Python Cheat Sheet
by Dave Child (DaveChild) via cheatography.com/1/cs/19/

Python sys Variables Python Class Special Methods Python String Methods (cont)

argv Command line args __new_​_(cls) __lt__​(self, other) istitle() * title() *

builti​n_m​odu​le_​names Linked C modules __init​__(​self, args) __le__​(self, other) isupper() * transl​ate​(table)

byteorder Native byte order __del_​_(self) __gt__​(self, other) join() upper() *

check_​int​erval Signal check __repr​__(​self) __ge__​(self, other) ljust(​width) zfill(​width)


frequency
__str_​_(self) __eq__​(self, other) lower() *
exec_p​refix Root directory
__cmp_​_(self, other) __ne__​(self, other) Methods marked * are locale dependant for 8-
executable Name of executable __inde​x__​(self) __nonz​ero​__(​self) bit strings.
exitfunc Exit function name
__hash​__(​self)
Python File Methods
modules Loaded modules
__geta​ttr​__(​self, name)
path Search path close() readli​nes​(size)
__geta​ttr​ibu​te_​_(self, name)
platform Current platform flush() seek(o​ffset)
__seta​ttr​__(​self, name, attr)
stdin, stdout, stderr File objects for I/O fileno() tell()
__dela​ttr​__(​self, name)
versio​n_info Python version info isatty() trunca​te(​size)
__call​__(​self, args, kwargs)
winver Version number next() write(​string)
Python List Methods read(size) writel​ine​s(list)
Python sys.argv
append​(item) pop(po​sition) readli​ne(​size)
sys.ar​gv[0] foo.py
count(​item) remove​(item)
Python Indexes and Slices
sys.ar​gv[1] bar extend​(list) reverse()
sys.ar​gv[2] -c len(a) 6
index(​item) sort()
sys.ar​gv[3] qux a[0] 0
insert​(po​sition, item)
sys.ar​gv[4] --h a[5] 5

sys.argv for the command: Python String Methods a[-1] 5

$ python foo.py bar -c qux --h capita​lize() * lstrip() a[-2] 4

center​(width) partit​ion​(sep) a[1:] [1,2,3​,4,5]


Python os Variables
count(sub, start, end) replac​e(old, new) a[:5] [0,1,2​,3,4]
altsep Altern​ative sep a[:-2] [0,1,2,3]
decode() rfind(sub, start ,end)
curdir Current dir string
encode() rindex​(sub, start, end) a[1:3] [1,2]
defpath Default search path a[1:-1] [1,2,3,4]
endswi​th(sub) rjust(​width)
devnull Path of null device
expand​tabs() rparti​tio​n(sep) b=a[:] Shallow copy of a
extsep Extension separator
find(sub, start, end) rsplit​(sep) Indexes and Slices of a=[0,1​,2,​3,4,5]
linesep Line separator
index(sub, start, end) rstrip()
name Name of OS Python Datetime Methods
isalnum() * split(sep)
pardir Parent dir string today() fromor​din​al(​ord​inal)
isalpha() * splitl​ines()
pathsep Patch separator now(ti​mez​one​info) combin​e(date, time)
isdigit() * starts​wit​h(sub)
sep Path separator utcnow() strpti​me(​date, format)
islower() * strip()
Registered OS names: "​pos​ix", "​nt", fromti​mes​tam​p(t​ime​stamp)
isspace() * swapcase() *
"​mac​", "​os2​", "​ce", "​jav​a", "​ris​cos​"
utcfro​mti​mes​tam​p(t​ime​stamp)

By Dave Child (DaveChild) Published 19th October, 2011. Sponsored by ApolloPad.com


cheatography.com/davechild/ Last updated 12th May, 2016. Everyone has a novel in them. Finish Yours!
www.getpostcookie.com Page 1 of 2. https://apollopad.com
Python Cheat Sheet
by Dave Child (DaveChild) via cheatography.com/1/cs/19/

Python Time Methods

replace() utcoff​set()

isofor​mat() dst()

__str__() tzname()

strfti​me(​format)

Python Date Formatting

%a Abbrev​iated weekday (Sun)

%A Weekday (Sunday)

%b Abbrev​iated month name (Jan)

%B Month name (January)

%c Date and time

%d Day (leading zeros) (01 to 31)

%H 24 hour (leading zeros) (00 to 23)

%I 12 hour (leading zeros) (01 to 12)

%j Day of year (001 to 366)

%m Month (01 to 12)

%M Minute (00 to 59)

%p AM or PM

%S Second (00 to 61⁴)

%U Week number¹ (00 to 53)

%w Weekday² (0 to 6)

%W Week number³ (00 to 53)

%x Date

%X Time

%y Year without century (00 to 99)

%Y Year (2008)

%Z Time zone (GMT)

%% A literal "​%" character (%)

¹ Sunday as start of week. All days in a new year preceding the


first Sunday are considered to be in week 0.
² 0 is Sunday, 6 is Saturday.
³ Monday as start of week. All days in a new year preceding the
first Monday are considered to be in week 0.
⁴ This is not a mistake. Range takes account of leap and double​-
leap seconds.

By Dave Child (DaveChild) Published 19th October, 2011. Sponsored by ApolloPad.com


cheatography.com/davechild/ Last updated 12th May, 2016. Everyone has a novel in them. Finish Yours!
www.getpostcookie.com Page 2 of 2. https://apollopad.com
PHP Cheat Sheet
by Dave Child (DaveChild) via cheatography.com/1/cs/2/

PHP Array Functions PHP Filesystem Functions Regular Expres​sions Syntax

array_diff (arr1, arr2 ...) clearstatcache () ^ Start of string

array_filter (arr, function) copy (source, dest) $ End of string

array_flip (arr) fclose (handle) . Any single character

array_intersect (arr1, arr2 ...) fgets (handle, len) (a|b) a or b

array_merge (arr1, arr2 ...) file (file) (...) Group section

array_pop (arr) filemtime (file) [abc] In range (a, b or c)

array_push (arr, var1, var2 ...) filesize (file) [^abc] Not in range

array_reverse (arr) file_exists (file) \s White space

array_search (needle, arr) fopen (file, mode) a? Zero or one of a

array_walk (arr, function) fread (handle, len) a* Zero or more of a

count (count) fwrite (handle, str) a*? Zero or more, ungreedy

in_array (needle, haystack) readfile (file) a+ One or more of a

a+? One or more, ungreedy


PHP String Functions PHP Date and Time Functions
a{3} Exactly 3 of a
crypt (str, salt) checkdate (month, day, year) a{3,} 3 or more of a
explode (sep, str) date (format, timestamp) a{,6} Up to 6 of a
implode (glue, arr) getdate (timestamp) a{3,6} 3 to 6 of a
nl2br (str) mktime (hr, min, sec, month, day, yr) a{3,6}? 3 to 6 of a, ungreedy
sprintf (frmt, args) strftime (formatstring, timestamp) \ Escape character
strip_tags (str, allowed_tags) strtotime (str) [:punct:] Any punctu​ation symbol
str_replace (search, replace, str) time () [:space:] Any space character
strpos (str, needle) [:blank:] Space or tab
PHP Regular Expres​sions Functions
strrev (str)
There's an excellent regular expression tester
strstr (str, needle) ereg (pattern, str) at: http:/​/re​gex​pal.com/

strtolower (str) split (pattern, str)

ereg_replace (pattern, replace, str) Pattern Modifiers


strtoupper (str)

substr (string, start, len) preg_grep (pattern, arr) g Global match

preg_match (pattern, str) i* Case-i​nse​nsitive


preg_match_all (pattern, str, arr) m* Multiple lines

preg_replace (pattern, replace, str) s* Treat string as single line

preg_split (pattern, str) x* Allow comments and whitespace in


pattern

By Dave Child (DaveChild) Published 19th October, 2011. Sponsored by CrosswordCheats.com


cheatography.com/davechild/ Last updated 13th May, 2016. Learn to solve cryptic crosswords!
www.getpostcookie.com Page 1 of 2. http://crosswordcheats.com
PHP Cheat Sheet
by Dave Child (DaveChild) via cheatography.com/1/cs/2/

Pattern Modifiers (cont) PHP Date Formatting (cont)

e* Evaluate replac​ement t Days in month (28 to 31)

U* Ungreedy pattern
a am or pm
* PCRE modifier
A AM or PM

PHP fopen() Modes B Swatch Internet Time (000 to 999)

r Read S Ordinal Suffix (st, nd, rd, th)

r+ Read and write, prepend


T Timezone of machine (GMT)
w Write, truncate
Z Timezone offset (seconds)
w+ Read and write, truncate
O GMT offset (hours) (+0200)
a Write, append
I Daylight saving (1 or 0)
a+ Read and write, append
L Leap year (1 or 0)

PHP Date Formatting


U Seconds since Epoch ³
Y 4 digit year (2008)
c ISO 8601 (PHP 5)
y 2 digit year (08)
(2008-​07-​31T​18:​30:​13+​01:00)
F Long month (January)
r RFC 2822 (Thu, 31 Jul 2008 18:30:13 +0100)
M Short month (Jan)
¹ 0 is Sunday, 6 is Saturday.
m Month ⁴ (01 to 12) ² Week that overlaps two years belongs to year that
n Month (1 to 12) contains most days of that week. Hence week
number for 1st January of a given year can be 53 if
D Short day name (Mon)
week belongs to previous year. date("W​", mktime(0,
l Long day name (Monday) (lowercase L)
0, 0, 12, 8, $year)) always gives correct number of
d Day ⁴ (01 to 31) weeks in $year.

j Day (1 to 31) ³ The Epoch is the 1st January 1970.


⁴ With leading zeroes

h 12 Hour ⁴ (01 to 12)

g 12 Hour (1 to 12)

H 24 Hour ⁴ (00 to 23)

G 24 Hour (0 to 23)

i Minutes ⁴ (00 to 59)

s Seconds ⁴ (00 to 59)

w Day of week ¹ (0 to 6)

z Day of year (0 to 365)

W Week of year ² (1 to 53)

By Dave Child (DaveChild) Published 19th October, 2011. Sponsored by CrosswordCheats.com


cheatography.com/davechild/ Last updated 13th May, 2016. Learn to solve cryptic crosswords!
www.getpostcookie.com Page 2 of 2. http://crosswordcheats.com
Regular Expressions Cheat Sheet
by Dave Child (DaveChild) via cheatography.com/1/cs/5/

Anchors Assertions Groups and Ranges

^ Start of string, or start of line in multi-line ?= Lookahead assertion . Any character except new line (\n)
pattern ?! Negative lookahead (a|b) a or b
\A Start of string
?<= Lookbehind assertion (...) Group
$ End of string, or end of line in multi-line
?!= or ?<! Negative lookbehind (?:...) Passive (non-c​apt​uring) group
pattern
?> Once-only Subexp​ression [abc] Range (a or b or c)
\Z End of string
?() Condition [if then] [^abc] Not (a or b or c)
\b Word boundary
?()| Condition [if then else] [a-q] Lower case letter from a to q
\B Not word boundary
?# Comment [A-Q] Upper case letter from A to Q
\< Start of word
[0-7] Digit from 0 to 7
\> End of word Quanti​fiers
\x Group/​sub​pattern number "​x"
* 0 or more {3} Exactly 3
Character Classes Ranges are inclusive.
+ 1 or more {3,} 3 or more
\c Control character
? 0 or 1 {3,5} 3, 4 or 5 Pattern Modifiers
\s White space
Add a ? to a quantifier to make it ungreedy. g Global match
\S Not white space
i* Case-i​nse​nsitive
\d Digit Escape Sequences
m* Multiple lines
\D Not digit
\ Escape following character s* Treat string as single line
\w Word
\Q Begin literal sequence x* Allow comments and whitespace in
\W Not word
\E End literal sequence pattern
\x Hexade​cimal digit
"​Esc​api​ng" is a way of treating characters e* Evaluate replac​ement
\O Octal digit
which have a special meaning in regular U* Ungreedy pattern
expres​sions literally, rather than as special
POSIX * PCRE modifier
charac​ters.

[:upper:] Upper case letters


String Replac​ement
Common Metach​ara​cters
[:lower:] Lower case letters
$n nth non-pa​ssive group
[:alpha:] All letters ^ [ . $
$2 "​xyz​" in /^(abc​(xy​z))$/
[:alnum:] Digits and letters { * ( \
$1 "​xyz​" in /^(?:a​bc)​(xyz)$/
[:digit:] Digits + ) | ?
$` Before matched string
[:xdigit:] Hexade​cimal digits < >
$' After matched string
[:punct:] Punctu​ation The escape character is usually \
$+ Last matched string
[:blank:] Space and tab
Special Characters $& Entire matched string
[:space:] Blank characters
\n New line Some regex implem​ent​ations use \ instead of $.
[:cntrl:] Control characters
\r Carriage return
[:graph:] Printed characters
\t Tab
[:print:] Printed characters and spaces
\v Vertical tab
[:word:] Digits, letters and underscore
\f Form feed

\xxx Octal character xxx

\xhh Hex character hh

By Dave Child (DaveChild) Published 19th October, 2011. Sponsored by CrosswordCheats.com


cheatography.com/davechild/ Last updated 12th May, 2016. Learn to solve cryptic crosswords!
www.getpostcookie.com Page 1 of 1. http://crosswordcheats.com