Developer's Closet A place where I can put my PHP, SQL, Perl, JavaScript, and VBScript code.

1Feb/120
PHP Regular Expression to Remove A Tag

I needed to remove a tag and all the text within a tag. Sounds easy enough. Here is the HTML:

$content = 'Hello <div id="tag_to_remove">I would like everything within these div tags to be removed!</div> World';
echo $content;

The desired results:

Hello World

Here is the PHP to remove the tag and all text within the tag:

$content = 'Hello <div id="tag_to_remove">I would like everything within these div tags to be removed!</div> World';
echo preg_replace('/<div id=\"tag_to_remove[\\d\\D]*?\/div>/','',$content);

The end results:

Hello World

 

Filed under: PHP No Comments
4Aug/100
file_put_contents() Function for PHP 4

I needed to run code I wrote for PHP 5 on a PHP 4 installation. Everything worked except the file_put_contents function. I scoured the web for a good implementation of the function for PHP 4 and I came across phpied.com here: http://www.phpied.com/file_get_contents-for-php4/. And the site is run on WordPress! Nicely done!

Here is his code:

if (!function_exists('file_put_contents')) {
    function file_put_contents($filename, $data) {
        $f = @fopen($filename, 'w');
        if (!$f) {
            return false;
        } else {
            $bytes = fwrite($f, $data);
            fclose($f);
            return $bytes;
        }
    }
}
Filed under: PHP No Comments
5May/090
Function to Create an Array from Database Results in PHP

This simple function will create an array out of the multi-dimensional rows returned from a database query.

function mysql_fetch_array_r($result,$result_type=MYSQL_NUM) {
	$arr = array();
	for($i=0;$i<@mysql_num_rows($result);$i++)  {
		array_push($arr,@mysql_fetch_array($result,$result_type));
	}
	return $arr[0]; // on error, $arr is empty
}
Tagged as: , No Comments
21Apr/090
Function to Format a Date in PHP

This is a really simple function to format a date.

function date_formatter($date) {
	return date("Y-m-d G:i:s",$date);
}
Tagged as: , No Comments
16Apr/090
Output File Size in PHP

Pass a file size to this function like this:

$filesize = get_file_size(2048);

And return a nicely formatted file size:

2 MB

// function to get file size and present in human readable format
function get_file_size($size) {
	$sizes = Array(' B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB');
	$ext = $sizes[0];
	for ($i=1; (($i = 1024)); $i++) {
		$size = $size / 1024;
		$ext  = $sizes[$i];
	}
	return number_format($size)." ".$ext;
}
Tagged as: , No Comments