Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder
    Join Date
    Jul 2002
    Location
    Canada, eh?
    Posts
    133
    Thanks
    2
    Thanked 3 Times in 3 Posts

    Code Extensions I Always Use

    Here are all of the "extensions" I use for all of my PHP games and sites. I decided to finally compile them and improve them, so figured I would share them. I don't think there is any equivelant PHP functions already, but I could be wrong.

    I am aware that some may be too memory intensive or something along those lines, but if you can find a better way to do what these functions are doing, then I invite you to do so.



    PHP Code:
    function al($a) {

      
    // Strips all but alphabetical characters from $a. If a second parameter
      // is specified, all characters in that string are kept as well. If the second
      // parameter is set to true instead of a string, then it will keep numeric characters
      // as well. If a third parameter is set to true, then it will also keep numeric characters.

      
    $extra "";
      if (
    func_num_args() >= 2) {
        if (
    func_get_arg(1) === true$extra "0123456789";
        else 
    $extra func_get_arg(1);
        if (
    func_num_args() >= && func_get_arg(2) === true$extra .= "0123456789";
      }
      
    $temp "";
      
    $aln "abcdefghijklmnopqrstuvwxyz".$extra;
      for (
    $b=0;$b<strlen($a);$b++) {
        
    $temp2 substr($a,$b,1);
        if (
    stristr($aln,$temp2)) {
          
    $temp .= $temp2;
        }
      }
      return 
    $temp;

    PHP Code:
    function checkwhite($a) {

      
    // Returns true if $a is only full of empty spaces (characters at or below ASCII 0032).
      // If a second parameter is specified, and is true, this will also check ASCII 0160 as an empty space.

      
    $temp true;
      
    $c160 false;
      if (
    func_num_args() >= && func_get_arg(1) === true$c160 true;
      for (
    $b=0;$b<strlen($a);$b++) {
        
    $temp2 ord(substr($a,$b,1));
        if (
    $temp2 32 && (!$c160 || $temp2 != 160)) {
          
    $temp false;
          break;
        }
      }
      return 
    $temp;

    PHP Code:
    function sw($a) {

      
    // Strips all but 1 space between words in $a. ASCII 0160 is treated as a space. Spaces
      // and empty characters are also removed from the front and back of $a.

      
    if (!eregi(" ",$a) && !eregi("*",$a)) return $a;
      
    $a str_replace("*"," ",$a);
      
    $as explode(" ",$a);
      
    $ns "";
      foreach (
    $as as $value) {
        if (
    $value != "") {
          if (
    $ns != ""$ns .= " ";
          
    $ns .= trim($value," \t\0\x0B");
        }
      }
      return 
    $ns;

    PHP Code:
    function hex($a) {

      
    // Simply makes a hex-color for HTML out of whatever string is
      // passed to it. If you pass "I like cheese and nachos!" to this
      // function, then it will return "#ECEEEA". Another example:
      // "##G08ED" would return "#08ED00" since it pads the right-side
      // with 0's.

      
    $a strtolower($a);
      
    $set "abcdef0123456789";
      
    $result "#";
      for (
    $i=0;$i<strlen($a);$i++) {
        if (
    eregi(substr($a,$i,1),$set)) {
          
    $result .= substr($a,$i,1);
        }
      }
      while (
    strlen($result) < 7) {
        
    $result .= "0";
      }
      
    $result substr($result,0,7);
      
    $result strtoupper($result);
      return 
    $result;

    PHP Code:
    function pluralize() {

      
    // Uses English logic to attempt to pluralize a word. If a second parameter is passed,
      // and is true, the pluralization will be capitalized. If the second parameter is an
      // integer, it will be checked if it is == 1, if it is, the first parameter will be
      // returned unaltered. If a third parameter is specified, that instead will be checked
      // to see if it is == 1, ignoring the second parameter.

      
    if (func_num_args() >= 1) {
        
    $vows "euioa";
        
    $cons "qwrtypsdfghjklzxcvbnm";
        
    $word func_get_arg(0);
        
    $add "";
        
    $cap false;
        
    $donum 0;
        if (
    func_num_args() >= 2) {
          if (
    func_get_arg(1) === true$cap true;
          else if (
    is_numeric(func_get_arg(1))) $donum func_get_arg(1);
          if (
    func_num_args() >= && is_numeric(func_get_arg(2))) $donum func_get_arg(2);
        }
        if (
    $donum == 1) return $word;
        if (
    is_string($word)) {
          
    $word trim($word);
          if (
    strlen($word) == 1$add "s";
          else {
            
    $last strtolower(substr($word,-1));
            
    $blast strtolower(substr($word,-2,1));
            if (!
    eregi($last,$vows) && !eregi($last,$cons)) $add "";
            else {
              if (
    $last != "s" && $last != "y"$add "s";
              else if (
    $last == "s") {
                if (
    $blast == "s" || eregi($blast,$vows)) $add "es";
                else 
    $add "'";
              }
              else {
                if (
    eregi($blast,$vows)) $add "s";
                else {
                  
    $word substr($word,0,(strlen($word)-1));
                  
    $add "ies";
                }
              }
            }
          }
          
    $add = ($cap) ? strtoupper($add) : strtolower($add);
          return 
    $word.$add;
        }
        return 
    $word;
      }
      return 
    false;

    PHP Code:
    function cutwords() {

      
    // Returns a string with all words occuring within the string truncated to 24
      // characters, or to the second parameter if specified. It will use the  character
      // to signify the word was truncated unless a third parameter is specified, then it
      // will use that. This will even truncate words within HTML tags (if properly formatted).

      
    if (func_num_args() == 0) return "";
      else 
    $c func_get_arg(0);
      
    $len 24;
      
    $chr "";
      if (
    func_num_args() >= 2$len func_get_arg(1);
      if (
    func_num_args() >= 3$chr func_get_arg(2);
      
    $c str_replace("<"," <",str_replace(">","> ",$c));
      
    $c str_replace("\t"," ",$c);
      
    $d explode(" ",$c);
      
    $onhtml false;
      foreach (
    $d as $key => $value) {
        if (
    substr($value,0,1) == "<" && !$onhtml$onhtml true;
        if (!
    $onhtml) {
          if (
    strlen($value) > $len) {
            
    $tt1 " <span class=\"toolong\" title=\"".$value."\">";
            
    $tt2 "</span> ";
            
    $d[$key] = str_replace($value,$tt1.substr($value,0,$len).$chr.$tt2,$d[$key]);
          }
        }
        if (
    substr($value,(strlen($value)-1),1) == ">" && $onhtml$onhtml false;
      }
      
    $c implode(" ",$d);
      return 
    str_replace(" <","<",str_replace("> ",">",$c));

    PHP Code:
    function getsuccess($rate) {

      
    // Returns true/false success rate based on a 0-100% basis. Decimals are supported up to 2, or
      // however many specified in the second parameter up to 12. getsuccess(12.5) will return true
      // 12.5% of the time, etc.

      
    $dec 2;
      if (
    func_num_args() >= && is_numeric(func_get_arg(1))) $dec floor(abs(func_get_arg(1)));
      if (
    $dec 12$dec 12;
      
    $n1 "1".str_repeat("0",$dec);
      
    $n2 "100".str_repeat("0",$dec);
      return (
    round(($rate*$n1),2) >= mt_rand(1,$n2)) ? truefalse;

    PHP Code:
    function gettimeformat($time) {

      
    // Will return a format of time based on $time seconds. If a second parameter is specified, then it will
      // use that internal format instead of the default. The format defaults to 2, as it's the most
      // proper english method of displaying time. This function only goes up to weeks, as months and years
      // do not have a constant amount of time.

      // The following are examples of the internal time format using 1341733 for $time:
      // 0 = 2w 1d 12h 42m 13s
      // 1 = 2 weeks, 1 day, 12 hrs, 42 mins, 13 secs
      // 2 = 2 Weeks, 1 Day, 12 Hours, 42 Minutes, 13 Seconds
      // 3 = Weeks: 2 - Days: 1 - Hours: 12 - Mins: 42 - Secs: 13

      
    $tf = array();
      
    $tf[0] = array();
      
    $tf[0]['w'] = "!w";
      
    $tf[0]['d'] = "!d";
      
    $tf[0]['h'] = "!h";
      
    $tf[0]['m'] = "!m";
      
    $tf[0]['s'] = "!s";
      
    $tf[0]['p'] = " ";
      
    $tf[1] = array();
      
    $tf[1]['w'] = "! week%";
      
    $tf[1]['d'] = "! day%";
      
    $tf[1]['h'] = "! hr%";
      
    $tf[1]['m'] = "! min%";
      
    $tf[1]['s'] = "! sec%";
      
    $tf[1]['p'] = ", ";
      
    $tf[2] = array();
      
    $tf[2]['w'] = "! Week%";
      
    $tf[2]['d'] = "! Day%";
      
    $tf[2]['h'] = "! Hour%";
      
    $tf[2]['m'] = "! Minute%";
      
    $tf[2]['s'] = "! Second%";
      
    $tf[2]['p'] = ", ";
      
    $tf[3] = array();
      
    $tf[3]['w'] = "Weeks: !";
      
    $tf[3]['d'] = "Days: !";
      
    $tf[3]['h'] = "Hours: !";
      
    $tf[3]['m'] = "Mins: !";
      
    $tf[3]['s'] = "Secs: !";
      
    $tf[3]['p'] = " - ";

      
    $res "";
      
    $format 2;
      if (
    func_num_args() >= && isset($tf[func_get_arg(1)])) $format func_get_arg(1);

      
    $ta = array();
      
    $ta['w'] = floor($time/604800);
      
    $ta['d'] = floor(($time-($ta['w']*604800))/86400);
      
    $ta['h'] = floor(($time-($ta['w']*604800)-($ta['d']*86400))/3600);
      
    $ta['m'] = floor(($time-($ta['w']*604800)-($ta['d']*86400)-($ta['h']*3600))/60);
      
    $ta['s'] = floor($time-($ta['w']*604800)-($ta['d']*86400)-($ta['h']*3600)-($ta['m']*60));
      foreach (
    $ta as $key => $value) {
        if (
    $value != 0) {
          if (
    $res != ""$res .= $tf[$format]['p'];
          
    $temp str_replace("!",number_format($value),$tf[$format][$key]);
          if (
    $value != 1$temp str_replace("%","s",$temp);
          
    $res .= $temp;
        }
      }
      if (
    $res == ""$res str_replace("!","0",$tf[$format]['s']);
      else 
    $res str_replace("%","",$res);
      return 
    $res;

    PHP Code:
    function suffix($a) {

      
    // Gets the suffix of the specified number $a.

      
    if (!is_numeric($a)) return $a;
      
    $a floor(abs($a));
      
    $ac = array("th","st","nd","rd");
      
    $b $ac[0];
      if (isset(
    $ac[substr($a,-1)]) && (strlen($a) < || substr($a,-2,1) != 1)) $b $ac[substr($a,-1)];
      return 
    $a.$b;

    PHP Code:
    function gettextualsize($bytes) {

      
    // Returns the textual size of $bytes in B/KB/MB. If a second parameter is specified, and evaluates to true,
      // then the textual representations of the size will be elongated. This does not support GB, TB, etc.

      
    $txt = array(" B"," KB"," MB");
      if (
    func_num_args() >= && func_get_arg(1) == true$txt = array(" Bytes"," Kilobytes"," Megabytes");

      if (
    $bytes 1024) return $bytes.$txt[0];
      else if (
    $bytes 1048576) return round($bytes/1024,2).$txt[1];
      else return 
    round($bytes/1048576,2).$txt[2];

    PHP Code:
    function truncate($a,$b) {

      
    // This cuts $a to $b length.
      // Unlike the substr() function, this truncates the text at the closest
      // space after the word. So if the $bth character is the "n" in "arrange",
      // then this will add 2 to $b, and return it's truncated state.
      // This is mainly used for news snippets.

      
    $brat $b;
      
    $temp "";
      if (
    strlen($a) >= $brat) {
        while (
    substr($a,$brat,1) != " " && $brat <= strlen($a)) {
          
    $brat++;
        }
        
    $temp substr($a,0,$brat);
      }
      else 
    $temp $a;
      return 
    $temp;

    Bored? Might as well play Fantasian Kingdoms: http://www.fantasiankingdoms.com/

    Check out my JavaScript Image Project: http://codingforums.com/showthread.php?t=185231

  • #2
    Regular Coder xconspirisist's Avatar
    Join Date
    Jun 2006
    Location
    Great Britain.
    Posts
    138
    Thanks
    1
    Thanked 6 Times in 6 Posts
    A couple of suggestions:

    1) The names of your functions are very confusing. I could only determine what the function does from reading the comments in your functions.

    2) Try using the docblock style of commenting your functions. For example:

    PHP Code:
    /**
     * A function that outputs "bar". 
     *
     * @param $a A variable that is unused, just here to demonstrate docblocks.
     * @return void
     */
    function foo($a "Unused") {
        echo 
    'bar';

    It is a standard format used by many programming languages, and pretty clear to read. The biggest advantage with them is that they can be interpreted by programs like doxygen.

    3) Your function, checkwhite() will be slower when compared to the php native function empty(), which would be faster and more thorough.

    4) At lot of your functions use heavy indenting where it is unnecessary. Do not encapsulate a whole function body in an if statement. If you're validating function arguments and the validation fails, return! It also makes your code a lot easier to read.
    If I have been helpful, use the "thank" button - It makes me happy!

    xconspirisist.co.uk - homepage of my online alias
    technowax.net - a community for people interested in all forms of modern technology.

  • #3
    Regular Coder
    Join Date
    Jul 2002
    Location
    Canada, eh?
    Posts
    133
    Thanks
    2
    Thanked 3 Times in 3 Posts
    Quote Originally Posted by xconspirisist View Post
    A couple of suggestions:

    1) The names of your functions are very confusing. I could only determine what the function does from reading the comments in your functions.

    2) Try using the docblock style of commenting your functions. For example:

    PHP Code:
    /**
     * A function that outputs "bar". 
     *
     * @param $a A variable that is unused, just here to demonstrate docblocks.
     * @return void
     */
    function foo($a "Unused") {
        echo 
    'bar';

    It is a standard format used by many programming languages, and pretty clear to read. The biggest advantage with them is that they can be interpreted by programs like doxygen.

    3) Your function, checkwhite() will be slower when compared to the php native function empty(), which would be faster and more thorough.

    4) At lot of your functions use heavy indenting where it is unnecessary. Do not encapsulate a whole function body in an if statement. If you're validating function arguments and the validation fails, return! It also makes your code a lot easier to read.
    1) The names are simple on some of them because I use them frequently and abbreviating them makes it easier on ME, not necessarily anyone else. Remember, these were just extensions I used, and I never ever meant for them to be used by anyone else until now, so I didn't take into account that they may be confusing.

    2) So suddenly there's an improper way to comment...? I have NEVER used someone else's PHP code, so I have NEVER encountered someone else's commenting style, and always use my own. I comment USUALLY in large blocks with /* and */ if before I comment I KNOW that the comment is going to be a large one (only for references to myself, as again, I don't code for others). If I start with a simple "// $a = Blah, $x = blahblah" but it turns out to be more than one line, I just continue using //.

    3) empty() does NOT do what I intended checkwhite() do. checkwhite() was intended for Usernames, making sure that the user hadn't simply held space or tried using alt+0160 for whatever sick reason they had. If they wanted a username of "0" then empty would return true, and disallow them.

    4) Ahaha, I know, eh? Man, was I high when I wrote those functions or what? I knew someone might point that out, then I'd laugh. The problem is I wrote SOME of them BEFORE I learned how to have variable arguments, then tacked that on, then some AFTER I learned it, and was all fanciful with "no input required" type of stuff, then the latest functions I wrote were normal.
    Bored? Might as well play Fantasian Kingdoms: http://www.fantasiankingdoms.com/

    Check out my JavaScript Image Project: http://codingforums.com/showthread.php?t=185231

  • #4
    Regular Coder ralph l mayo's Avatar
    Join Date
    Nov 2005
    Posts
    951
    Thanks
    1
    Thanked 31 Times in 29 Posts
    Using default arguments is much more idiomatic in PHP than func_num_args and friends (thankfully). Typically each function should serve one purpose and bolting on functionality with extra arguments is bad style. Providing polymorphic behavior for the same number of inputs is great (ie, making it work on ints and strings transparently), but trailing booleans and stuff usually indicate either you need more than one function, that the function should operate on a callback to allow client-defined behavior, or that the function wants to be a class providing diverse methods to work on similar data.

    Speaking of classes, utility stuff like this belongs in the private implementations of classes and not in the global namespace. It's bad enough trying to remember the 52,000 functions in the PHP core without having to remember a dozen more for each coder's util.php.

    To provide something constructive, here's the first group of functions in regexp:

    PHP Code:
    function strip_non_alpha($str$extra '')
    {
        return 
    preg_replace('/[^[:alpha:]' preg_quote($extra) . ']/xms'''$str);
    }

    function 
    is_all_lower_ascii($str$include_160 false)
    {
        
    $class = ($include_160) ? '\x00-\x20' '\xA0\x00-\x20';
        return 
    preg_match("/\A[$class]*\z/xms"$str);
    }

    function 
    compact_spaces($str)
    {
        return 
    preg_replace('/\b\W+\b/xms'' '$str);
    }

    function 
    coerce_hex_color_code($str)
    {
        return 
    sprintf('#%06.6s'preg_replace('/[^a-fA-F\d]/xms'''$str));

    I think I heard marek say he wants to rewrite the other ones


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •