PHP Cheat Sheet: Regular Expression

1. preg_match():

if (preg_match("/php/i", "PHP is the web scripting language of choice.")) {
    echo "A match was found.";

Note: $matches[0]will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.

$str =;
if (preg_match('@^(?:http://)?([^/]+)@i', $str, $matches) {
    $host = $matches[1];

2. preg_match_all():

$str = "<b>example: </b><div align=left>this is a test</div>";
preg_match_all("|<[^>]+>(.*)</[^>]+>|U", $str, $out);
echo $out[0][0];  // "<b>example: </b>"
echo $out[0][1];  // "<div align=left>this is a test</div>"
echo $out[1][0];  // "example: "
echo $out[1][1];  // "this is a test"


$userinfo = "Name: <b>Joe Black</b> <br> Title: <b>PHP Guru</b>";
preg_match_all("/<b>(.*)<\/b>/U", $userinfo, $pat_array);
echo $pat_array[0][0];  // "Joe Black"
echo $pat_array[0][1];  // "PHP Guru"

3. preg_replace():

The preg_replace() function replaces all occurrences of pattern with replacement, and returns the
modified result.

$text = "This is a link to";
echo preg_replace("/http:\/\/(.*)\//", "<a href=\"\${0}\">\${0}</a>", $text);
// "This is a link to
// <a href=""></a>."

If you pass arrays as the pattern and replacement parameters, the function will cycle through each
element of each array, making replacements as they are found.

$draft = "In 2010 the company faced plummeting revenues and scandal.";
$keywords = array("/faced/", "/plummeting/", "/scandal/");
$replacements = array("celebrated", "skyrocketing", "expansion");
echo preg_replace($keywords, $replacements, $draft);
// "In 2010 the company celebrated skyrocketing revenues and expansion."

4. Regular Expression Modifiers

  • i:     case-insensitive
  • m:     Treat a string as several (m for multiple) lines. By default, the ^ and $ characters match at the very start and very end of the string in question. Using the m modifier will allow for ^ and $ to match at the beginning of any line in a string.
  • s:    Let a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded.
  • U:    Turns off greety matching.

Read More

PHP Cheat Sheet: Working with Directories

1. Retrieving a Path’s Filename:

$path = '/home/www/data/users.txt';
$file_nm = basename($path);  // "users.txt"
$file_nm_1 = basename($path, ".txt");  // "users", no extension.

2. Retrieving a Path’s Directory:

$path = '/home/www/data/users.txt';
$dir_nm = dirname($path)  // "/home/www/data"

3. Learning More about a Path:

$pathinfo = pathinfo('/home/www/htdocs/book/chapter10/index.html');
echo $pathinfo['dirname'];   // "/home/www/htdocs/book/chapter10"
echo $pathinfo['basename'];   // "index.html"
echo $pathinfo['extension'];   // "html"
echo $pathinfo['filename'];   // "index"

4. Identifying the Absolute Path

$imgPath = '../../images/cover.gif';
$absolutePath = realpath($imgPath);   // "/www/htdocs/book/images/cover.gif"

5. opendir() and readdir()

if ($dh = @opendir($directory)) {
    while (($filename = readdir ($dh))) {
        if ($filename != "." && $filename != "..") {
            if (is_file($directory."/".$filename)) {
                echo "File: $filename";
            if (is_dir($directory."/".$filename)) {
                echo "Dir: $filename";


Read More

PHP Cheat Sheet: File Handling

1. Checking Whether a File Exists:

if (file_exists("testfile.txt")) echo "File exists";

2. Reading from Files:

Method 1: Using fgets() to read one line a time:

$fh = fopen("testfile.txt", 'r') or die("Cannot open file.");
while (!feof($fh)) {
    $line = fgets($fh);
    $out .= $line;


Method 2: Using file_get_contents() to read the entire content:

$userfile= file_get_contents('users.txt');

3. Writing Files:

Method 1: Using fwrite():

// Regular writing, no locking.
$fh = fopen("testfile.txt", 'w') or die("Failed to create file");
fwrite($fh, $text) or die("Could not write to file");

// Writing with locking
$fh = fopen("testfile.txt", 'w') or die("Failed to create file");
flock($fh, LOCK_EX) or die("Cannot lock file");
fwrite($fh, $text) or die("Cannot not write to file");
flock($fh, LOCK_UN) or die ("Cannot unlock file");

// File append
$fh = fopen("testfile.txt", 'a') or die("Failed to create file");
fwrite($fh, $text) or die("Could not write to file");

Method 2: Using file_put_contents():

// No appending
file_put_contents('output.txt', $data) or die("Cannot write file");

// File append
file_put_contents('output.txt', $data, FILE_APPEND) or die("Cannot write file");

4. Determining a File’s Last Modified Time:

echo "File last updated: ".date("m-d-y g:i:sa", filemtime($file));

5. Determining a File’s Size:

$bytes = filesize($file);
$kilobytes = round($bytes/1024, 2);


Read More