Formatting text
There is often the situation in software development of wanting to format text, to create a message or show a warning etc.
One way to do this would be to concatanate text together. However this is quite a messy solution.
So...
echo "An error occured on " . $websiteName . " the error states " . $errorText . " please try to " . $error solution.
A better solution would be to use a formatted string, with
sprintf function.
echo sprintf("An error occured on %s the error states %s please try to %s", $websiteName, $errorText, $error solution);
An even simpler way to do this would be to use
printf which would print the formatted text straight to the screen, which uses
the same format string as
sprintf.
printf("An error occured on %s the error states %s please try to %s", $websiteName, $errorText, $error solution);
The
%s symbols means that a string argument will appear in that point in the string. The arguments are placed in the order
of they are in, in the argument list. So in the above example it means websiteName comes first and then errorText.
The number of arguments in the string must match the number of arguments in the function, otherwise an error will be thrown.
To use the same argument more than once in a string you can number the arguments as shown below, were the argument
name is used twice.
$name = "Tom";
$food = "apple";
printf("%1$s went to the shops to buy a %2$s, which %1$s was very pleased with.", $name, $food);
Formatted strings can also be useful for representing SQL statements, were another feature of formatted strings comes to the fore, specifying types.
This allows types to be treated properly.
$type = "C";
$sql = sprintf("SELECT * FROM Users WHERE UserType = '%c'", $type);
This ensures that the $type variable is output as a Char and not anyother type.
No comments have been provided.
Written by Dominic Skinner
Last Updated: 2011-10-25 16:00:38