You are on page 1of 5

Working with printf()

printf() requires a string argument, known as a format control string.

printf ("This is my number: %d", 55);


A conversion specification begins with a percent (%) symbol and defines how to
treat the corresponding argument to printf().
printf() and Type Specifiers
Type Specifiers

Specifier

Description

Displays an argument as a decimal number

Displays an integer as a binary number

Displays an integer as its ASCII equivalent

Displays an integer as a floating-point number (double)

Displays an integer as an octal number (base 8)

Displays an argument as a string

Display an integer as a lowercase hexadecimal number (base 16)

Displays an integer as an uppercase hexadecimal number (base 16)

<?php
$number = 543;
printf("Decimal: %d<br/>", $number );
printf("Binary: %b<br/>", $number );
printf("Double: %f<br/>", $number );
printf("Octal: %o<br/>", $number );
printf("String: %s<br/>", $number);
printf("Hex (lower): %x<br/>", $number );
printf("Hex (upper): %X<br/>", $number );
?>
$red = 204;
$green = 204;
$blue = 204;
printf( "#%x%x%x", $red, $green, $blue);
Padding Output with the Padding Specifier
printf("%04d", 36);
printf ( "%'x4d", 36 );

Specifying a Field Width


print "<pre>";
printf ("%20s\n", "Books");
printf ("%20s\n", "CDs");
printf ("%20s\n", "Games");
printf ("%20s\n", "Magazines");
printf ("%-20s\n", "Left aligned");
print "</pre>";
Specifying Precision
printf( "%.2f", 5.333333);
<?php
$products = array (
"Green armchair"=>222.4,
"Candlestick"=>4,
"Coffee table"=>80.6
);
print "<pre>";
printf ("%-20s%23s\n", "Name", "Price");
printf ("%'-43s\n", "");
foreach ( $products as $Key=>$val ) {
printf ("%-20s%20.2f\n", $Key, $val);
}
print "</pre>";
?>

Storing a Formatted String


sprintf() returns a string you can then store in a variable

$dosh = sprintf("%.2f", 2.334454);


print "You have $dosh dollars to spend";
Finding the Length of a String with strlen()
strlen() to determine the length of a string.
if ( strlen( $membership ) == 4 ) {
print "Thank you!";
} else {
print "Your membership number must have 4 digits";
}
Finding a Substring Within a String with strstr()
strstr() to test whether a string exists embedded within another string.

$membership = "pAB7";
if ( strstr( $membership, "AB") ) {
print "Thank you. Don't forget that your membership expires soon!";
} else {
print "Thank you!";
}
Finding the Position of a Substring with strpos()
strpos() tells you both whether a string exists within a larger string and where it
is to be found.

$membership = "mz00xyz";
if ( strpos($membership, "mz") === 0 ) {
print "hello mz";
}
Extracting Part of a String with substr()
substr() return a portion of a string based on the start index and length of the
portion for which you are looking

strstr() demands two arguments�a source string and the starting index. It returns
all the characters from the starting index to the end of the string you are
searching. substr() optionally accepts a third argument, which should be an integer
representing the length of the string you want returned. If this argument is
present, substr() returns only the number of characters specified from the start
index onward:

$test = "scallywag";
print substr($test,6); // prints "wag"
print substr($test,6,2);
$test = "matt@corrosive.co.uk";
if ( $test = substr( $test, -3 ) == ".uk") {
print "Don't forget our special offers for British customers";
} else {
print "Welcome to our shop!";
}

Tokenizing a String with strtok()


strtok() initially requires two arguments, the string to be tokenized and the
delimiters by which to split the string. The delimiter string can include as many
characters as you want. strtok() returns the first token found, and afterstrtok()
has been called for the first time, the source string is cached

<?php
$test = "http://p24.corrosive.co.uk/tk.php";
$test .= "?id=353&sec=44&user=harry&context=php";

$delims = "?&";
$word = strtok( $test, $delims );
while ( is_string( $word ) ) {
if ( $word ) {
print "$word<br/>";
}
$word = strtok( $delims );
}
?>

Cleaning Up a String with trim(), Itrim(), and strip_tags()

trim() shaves any white space characters, including newlines, tabs, and spaces,
from both the start and end of a string. It accepts the string to be modified,
returning the cleaned-up version

$text = "\t\t\tlots of room to breathe";

$text = trim( $text );

print $text;

$text = "\t\t\tlots of room to breathe ";


$text = rtrim( $text );
print $text;

$text = "\t\t\tlots of room to breathe "; $text = ltrim( $text ); print


"<pre>$text</pre>";

PHP by its nature tends to work with markup text. It is not unusual to have to
remove tags from a block to present it without formatting. PHP provides the
strip_tags() function, which accepts two arguments, for this purpose. The first
argument it accepts is the text to transform. The second argument is optional and
should be a list of HTML tags that strip_tags() can leave in place.

$string = "<p>I <i>simply</i> will not have it,";


$string .= "<br/>said Mr Dean</p><b>The end</b>";
print strip_tags( $string, "<br/>" );

Replacing a Portion of a String Using substr_replace()


substr_replace() works similarly to substr() except it enables you to replace the
portion of the string you extract. The function requires three arguments: the
string you are transforming, the text you want to add to it, and the starting
index. It also accepts an optional length argument.

<?
$membership = "mz99xyz";
$membership = substr_replace( $membership, "00", 2, 2);
print "New membership number: $membership<br/>";
// prints "New membership number: mz00xyz"
?>

Replacing Substrings Using str_replace()


str_replace() replaces all instances of a string within another string. It requires
three arguments: a search string, the replacement string, and the string on which
this transformation is to be effected.

$string = "Site contents copyright 2003."; $string .= "The 2003 Guide to All Things
Good in Europe"; print str_replace("2003","2004",$string);

<?php $source = array( "The package which is at version 4.2 was released in 2000",
"The year 2000 was an excellent period for PointyThing4.2" ); $search =
array( "4.2", "2000" ); $replace = array ( "5.0", "2001" ); $source =
str_replace( $search, $replace, $source ); foreach ( $source as $str ) print
"$str<br>";

When str_replace() is passed an array of strings for its first and second
arguments, it attempts to switch each search string with its corresponding replace
string in the text to be transformed. When the third argument is an array, the
str_replace() returns an array of strings. The search and replace operations are
executed upon string in the array.

Converting Case
$membership = "mz00xyz";
$membership = strtoupper( $membership );
$home_url = "WWW.CORROSIVE.CO.UK";
$home_url = strtolower( $home_url );
if ( ! ( strpos ( $home_url, "http://") === 0) )
$home_url = "http://$home_url";
print $home_url;

$full_name = "violet elizabeth bott";


$full_name = ucwords ( $full_name );
print $full_name; // prints "Violet Elizabeth Bott"
$full_name = "VIolEt eLIZaBeTH bOTt";
$full_name = ucwords( strtolower($full_name) );
print $full_name; // prints "Violet Elizabeth Bott"

$string = "one line\n";


$string .= "another line\n";
$string .= "a third for luck\n";
print nl2br( $string );
nl2br() is a convenient method that converts every newline into an HTML break.

wordwrap() wraps lines every 75 characters and uses \n as its line-break character.
$string = "Given a long line, wordwrap() is useful as a means of";
$string .= "breaking it into a column and thereby making it easier to read";
print wordwrap($string);

print wordwrap( $string, 24, "<br/>\n");

$string = "As usual you will find me at http://www.witteringonaboutit.com/";


$string .= "chat/eating_green_cheese/forum.php. Hope to see you there!";
print wordwrap( $string, 24, "<br/>\n", 1 );

Breaking Strings into Arrays with explode()


explode(), though, breaks up a string into an array, which you can then store,
sort, or examine as you want.

$start_date = "2000-01-12";
$date_array = explode ("-",$start_date);
$date_array[0] == "2000"
$date_array[1] == "01"
$date_array[2] == "12"

You might also like