PHP
  Home arrow PHP arrow Page 6 - String Theory
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

String Theory
By: Vikram Vaswani, (c) Melonfire
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 12
    2001-09-20


    Table of Contents:
  • String Theory
  • Secret Agent Man
  • Running Backwards
  • Getting Into Position
  • Instant Paralysis
  • A Quick Trim
  • Working The Web

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    String Theory - A Quick Trim
    ( Page 6 of 7 )

    If you're looking to perform a little cosmetic surgery on your strings, a good place to start is the family of trim() functions. The most useful of these, trim(), is constructed specifically to remove whitespace from the beginning and end of a string. This comes in handy if you need to remove whitespace from a value prior to using it elsewhere (a database insert, maybe?)

    <? $str = " ever seen a white pigeon?"; // returns "ever seen a white pigeon?" echo trim($str); ?>
    It's also a good idea to use the trim() function on data entered into online forms, in order to ensure that your error-checking routines don't miss entries containing only whitespace. Here's an example which illustrates what I mean:

    <? $search = " "; // bad code, will not identify that search string // actually contains nothing if ($search != "") { perform_search(); } // good code, will account for whitespace-only entries if (trim($search) != "") { perform_search(); } ?>
    You can also use the ltrim() and rtrim() functions, which remove whitespace from the beginning and end of a string respectively.

    The next few string functions come in very handy when adjusting the case of a text string from lower- to upper-case, or vice-versa:

    strtolower() - convert string to lower case strtoupper()- convert string to upper case ucfirst() - convert the first character of string to upper case ucwords() - convert the first character of each word in string to upper case

    Here's an example:

    <? $str = "Something's rotten in the state of Denmark"; // returns "something's rotten in the state of denmark" echo strtolower($str); // returns "SOMETHING'S ROTTEN IN THE STATE OF DENMARK" echo strtoupper($str); // returns "Something's rotten in the state of Denmark" echo ucfirst($str); // returns "Something's Rotten In The State Of Denmark" echo ucwords($str); ?>
    You've already used the print() function extensively to display output. However, the print() function doesn't allow you to format output in any significant manner - for example, you can't write 1000 as 1,000 or 1 as 00001. And so the clever PHP developers came up with the sprintf() function, which allows you to define the format in which data is output.

    Consider the following example:

    <? // returns 1.6666666666667 print(5/3); ?>
    As you might imagine, that's not very friendly. Ideally, you'd like to display just the "significant digits" of the result. And so, you'd use the sprintf() function:

    <? // returns 1.67 echo sprintf("%1.2f", (5/3)); ?>
    A quick word of explanation here: the PHP sprintf() function is very similar to the printf() function that C programmers are used to. In order to format the output, you need to use "field templates", templates which represent the format you'd like to display.

    Some common field templates are:

    %s string
    %d decimal number
    %x hexadecimal number
    %o octal number
    %f float number

    You can also combine these field templates with numbers which indicate the number of digits to display - for example, %1.2f implies that PHP should only display two digits after the decimal point. If you'd like the formatted string to have a minimum length, you can tell PHP which character to use for padding by prefixing it with a single quote (').

    Here are a few more examples of sprintf() in action:

    <? // returns 00003 echo sprintf("%05d", 3); // returns $25.99 echo sprintf("$%2.2f", 25.99); // returns ****56 echo sprintf("%'*6d", 56); ?>
    In addition to the sprintf() function, PHP also offers the strpad() function, which is used for padding strings to a specific length. This function accepts a string or string variable as argument, together with the minimum string length required; a couple of optional arguments allow you to also specify which character to use for padding, and the direction in which padding is to take place.

    Here are a couple of examples:

    <? $str = "da bomb"; // returns "da bomb " echo str_pad($str, 10); // returns "da bomb###" echo str_pad($str, 10, "#"); // returns "***da bomb" echo str_pad($str, 10, "*", STR_PAD_LEFT); ?>
    Finally, the wordwrap() function can be used to break long sentences at a specified length.

    <? $str = "It's been ten years since Dr. Hannibal \"The Cannibal\" Lecter (Anthony Hopkins) escaped from a maximum-security penitentiary - ten years in which he's roamed free, indulging his very specialized tastes. But out of sight is very definitely not out of mind - he still haunts Clarice Starling (Julianne Moore), now a special agent in the FBI."; // returns a word-wrapped block of width 50 characters /* It's been ten years since Dr. Hannibal "The Cannibal" Lecter (Anthony Hopkins) escaped from a maximum-security penitentiary - ten years in which he's roamed free, indulging his very specialized tastes. But out of sight is very definitely not out of mind - he still haunts Clarice Starling (Julianne Moore), now a special agent in the FBI. */ echo wordwrap($str, 50); ?>


     
     
    >>> More PHP Articles          >>> More By Vikram Vaswani, (c) Melonfire
     

       

    PHP ARTICLES

    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
    Stay green...Green IT