CSI: PHP

"Looking at your tweets I cannot even fathom what your job is. CSI:PHP?" — @grmpyprogrammer

Who Needs Regular Expressions?

| Comments

Thanks to Moses Ngone for submitting this super sweet router snippet.

Moses writes:

“If the regular expression route gets tough, be more specific.”

Indeed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php

$vars = str_replace(".php", "", $_SERVER['REQUEST_URI']);
$vars = str_replace(".html", "", $vars);
$vars = str_replace("pics/",'',$vars);
$vars = str_replace("/pics",'',$vars);
$vars = str_replace("pix/",'',$vars);
$vars = str_replace("/pix",'',$vars);
$vars = str_replace("photos/",'',$vars);
$vars = str_replace("/photos",'',$vars);
$vars = str_replace("photo/",'',$vars);
$vars = str_replace("/photo",'',$vars);
$vars = str_replace("gallery/",'',$vars);
$vars = str_replace("/gallery",'',$vars);
$vars = str_replace("galleries/",'',$vars);
$vars = str_replace("/galleries",'',$vars);
$vars = str_replace("//","/",$vars);
$var_array = explode("/",$vars);

Pro tip: If you find yourself doing something like this, don’t. There are tons of excellent PHP frameworks that take care of routing for you. If you really want to write your own, spend some time reading some framework’s source code and unit tests to see how a few other folks have done it.

Comments