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 = http://www.php.net/index.html; if (preg_match(‘@^(?:http://)?([^/]+)@i’,…

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’];   //…

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; } fclose($fh); Method 2: Using file_get_contents()…

read more