Posts tagged 'remove'

How to Remove a (non-empty) Directory using PHP

Posted on September 28, 2008, Filled under PHP,  Bookmark it

Hello coders,

Here’s a snippet that can help you to remove a non-empty directory from the server. It’s a recursive function that deletes the directory with its files, folders and sub-folders.

<?php
function delete_directory($dir)
{
if ($handle = opendir($dir))
{
$array = array();

    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {

			if(is_dir($dir.$file))
			{
				if(!@rmdir($dir.$file)) // Empty directory? Remove it
				{
                delete_directory($dir.$file.'/'); // Not empty? Delete the files inside it
				}
			}
			else
			{
               @unlink($dir.$file);
			}
        }
    }
    closedir($handle);

	@rmdir($dir);
}

}

$dir = '/home/path/to/mysite.com/folder_to_delete/'; // IMPORTANT: with '/' at the end

$remove_directory = delete_directory($dir);
?>

How to remove an extension from a filename

Posted on September 4, 2008, Filled under PHP,  Bookmark it

If you need for any reason to remove an extension from a filename (string) this snippet can help you. An extension in this case is everything after the last period from the whole string.

<?php
/*
Source: Bit Repository (http://www.bitrepository.com/)
*/
function remove_filename_extension($filename)
{
$extension = strrchr($filename, ".");

$filename = substr($filename, 0, -strlen($extension));

return $filename;
}

$filename = 'This-is-a-photo-description.jpeg';

$str = remove_filename_extension($filename);

echo $str;
?>

PHP: How to remove empty values from an array

Posted on May 21, 2008, Filled under PHP,  Bookmark it

This function removes empty values from an array. This is useful if you’re working with dynamical arrays (for instance data harvested from a web site).

<?php
/*
Credits: Bit Repository
URL: http://www.bitrepository.com/web-programming/php/remove-empty-values-from-an-array.html
*/
function remove_array_empty_values($array, $remove_null_number = true)
{
	$new_array = array();

	$null_exceptions = array();

	foreach ($array as $key => $value)
	{
		$value = trim($value);

        if($remove_null_number)
		{
	        $null_exceptions[] = '0';
		}

        if(!in_array($value, $null_exceptions) && $value != "")
		{
            $new_array[] = $value;
        }
    }
    return $new_array;
}
?>

Example of usage:

$array = array("white", "yellow", 0, "green", " ", "navy");

$remove_null_number = true;
$new_array = remove_array_empty_values($array, $remove_null_number);

echo '<pre>'; print_r($new_array); echo '</pre>';

The new array will look like this:

Array
(
    [0] => white
    [1] => yellow
    [2] => green
    [3] => navy
)

NOTE: If you wish to keep the null number (0) then set the variable $remove_null_number to false.