Bulk “One Line” PHP scripts
Below scripts will be more useful for PHP developers to make their coding fast and efficiency.
1) Eliminate duplicate (or more) characters in a string (the underscore in the example below):
$text = preg_replace('#(_)+#','_',$text);
2) Randomly select of one element out of an array:
$image = $image_array[array_rand($image_array)];
3) Pass the htaccess/htpassword authenticated user to a script:
$user = $_SERVER['REMOTE_USER'];
4) Debug $_GET variables by displaying the whole search string:
echo $_SERVER['QUERY_STRING'];
5) Read a flat file (file.txt in this example) in as an array and remove line breaks:
$newArray = preg_replace("#\r\n?|\n#","",file('file.txt'));
6) Scrub html output:
$output = strtr($output,array('&'=>'&','<'=>'<','>'=>'>'));
7) Validate the format of an email address:
if (!preg_match("(^[-\w\.]+@([-a-z0-9]+\.)+[a-z]{2,4}$)i", $email)) echo "Email address $email is not valid";
8 ) Validate the format of a domain name:
if (!preg_match("(^([-a-z0-9]+\.)+[a-z]{2,4}$)i", $domain)) echo "Domain name $domain is not valid";
9) Validate the format of the user name and verify valid MX records for the domain name (OK, so it is two lines):
list($username, $domaintld) = split("@", $email, 2);
if (!getmxrr($domaintld, $mxrecords) OR !preg_match("(^[-\w\.]+$)", $username)) echo "Email address $email is not valid";
10) Remove one element from an array (in this example remove $image from array $image_array):
$image_array = array_merge(array_diff($image_array,(array)$image));
11) Randomly select of one element out of an array:
$image = $image_array[array_rand($image_array)];
12) Include using a full unix path while still maintaining script portability:
include($_SERVER['DOCUMENT_ROOT'] . '/file.inc');
Note: If u found any error, report me.


August 5th, 2009 at 10:14 AM
hmm..! good collection of stuff…
August 5th, 2009 at 4:58 PM
hi vijay……ur blog having useful content for php developers…my feedback is the index page each post bottom display[...] like this…if u change “readmore” and give the link…i think it’s better
thank u
August 5th, 2009 at 6:24 PM
Surely prem, i will update it soon. Thanks for your valuable feedback’s. keep posting.
August 5th, 2009 at 10:44 PM
Great collection. I will work it on above stuffs & i will comment.