Online
 
Friday, 09 January 2009
 
 
More article:
Related Content:

Formatting Strings
 
Article Index
Formatting Strings
Page 2
Page 3
Page 4


This script outputs log (15.32) = 2.72916. For those of you who come from the C language, note that printf() does not provide any kind of substitution of backslash-escaped special characters, such as \n. If you want to use these special characters, ensure that you specify the value of format_specification using the double-quote syntax.

The traditional C implementation of printf() requires that a parameter be specified for each replacement directive stored in format_specification. As the directives are found, the interpreter moves from one parameter to the next until all substitutions are made.

Unfortunately, this approach can cause some serious trouble. Consider the case, for example, of using printf() as the basis for a system that supports multiple languages. The English sentence

"The [box/case] contains [three/five] pens"

can be translated into another language using a different construction, for example:

"There are [three/five] pens in the [box/case]"

It's clear that using printf() to provide a localization system flexible enough to support the construction forms of different languages would be difficult without the possibility of specifying which parameter should be used to provide a value for each replacement directive.

Luckily, PHP makes it possible to do so by using a slightly different directive syntaxall you need to do is prepend the number of the parameter, followed by a dollar sign ($), to the directive. For example, the following script:

<?php

function replace_me ($s)
{
printf ($s, 10, 'box');
}

replace_me ("There are %d pens in the %s\n");
replace_me ("The %2\$s contains %1\$s pens\n");

?>

returns the correct value despite the fact that the order of the parameters is inverted in the second string (notice how I have escaped the dollar signs using a backslash to ensure that they are not trapped by PHP's string declaration mechanism):

There are 10 pens in the box.

The box contains 10 pens.

The sprintf function takes the same parameters as printf(), but returns the string that results from its execution:

$a = printf ("%d cases of wine\n", 10);

Tags: Add more tags...,
This entry was posted on . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a comment. Tags: Simple PHP, Pear, Easy PHP, PHP Tutorial, PHP MySQL, XSLT, Sap Tutorial, CSS Tutorial, XSL FO Java, SQL Tutorial.
Users' Comments (0)

Comment an article
  Name
  E-mail
   Title
Available characters: 4000
 Notify me of follow-up comments
This image contains a scrambled text, it is using a combination of colors, font size, background, angle in order to disallow computer to automate reading. You will have to reproduce it to post on my homepage
Enter what you see:

No comment posted

Wallpaper 65
Statistic


Last Post

 
Top! Top!