Development Resource Project
Native Linux Space Warfare: Freespace 2
Symfony 2 Crash Course
Nice n' Easy JQuery Image Rotator
JQuery Venetian Blinds Transition Effect
Scrollable Tables with Floating Header using CSS

PHP Snippets

Saturday, 2 August 08, 1:22 pm

Closing HTML Tags for a snippet

The XML DOM class which comes built-in to PHP as standard offers the ability to fix the markup in an HTML snippet. Say for instance you have a string of HTML code $htmlCode and wish to show a preview on a webpage, you could do the following:
$htmlSnippet = substr($htmlCode, 0, 500); $snippetMaker = new DOMDocument(); @$snippetMaker->loadHTML($htmlSnippet); echo $snippetMaker->saveHTML();
Note that we suppress warnings generated by the loadHTML() function by prefixing it with an at symbol @.

Random Password Generator

Several times I've come across some rather long-winded solutions to the problem of generating a random string of characters, e.g. for a random password or capcha text for instance.

It's easy to do this using just two lines of PHP, no need for anything complicated:

   for ($count = 0; $count < $password_length; $count++)
      $pword .= chr(rand(65, 90));

The PHP chr() function returns the character with the ASCII value passed in, and the characters with ASCII between 65 and 90 are the capital letters. So this generates a string of random capital letters, eg LXYJNGXOPN. For better passwords, you can include a greater range of ASCII characters. Obviously you only want typable ones, and usually only familiar special characters. The range 33 to 126 includes numbers, lowercase letters and the standard special typable characters. You get passwords such as ^^@1nM+Gx8 and Ov`3[|m3]M. However you often just want numbers and upper/lowercase letters. It's not hard to alter the script to accomplish this:
for ($count = 0; $count &lt; $password_length; $count++) { $ascii_code = rand(55, 115); if ($ascii_code &lt; 65) { $ascii_code -= 7; } elseif ($ascii_code >90) { $ascii_code += 6; } $password .= chr($ascii_code); }
Obviously you just need to set $password_length appropriately beforehand, and hey presto, you get a random password up to that length in the $password variable at the end. These passwords only contain numbers and letters, for example, sAT5Z96hYe and PsOZUZqJT7.

Collapse Whitespace within a String

This is really a PERL Regular Expression tip rather than PHP, but because of PHP's support for RegEx, is readily usable in a PHP script:

echo preg_replace('/\s+/', ' ', $string);

Trying to Work Out What the Fuck Character Set A String Contains

$heading = substr($response, stripos($response, '&lt;textarea'), 63); $len = strlen($heading); // NOT mb_strlen! for($i=0; $i&lt; $len;++$i) { echo $heading[$i], ' = ', dechex(ord($heading[$i])), '&lt;br />';   }
Leave Comment

/xkcd/ Who?

About This Page