SakhaliaNetHome PageSahara TerritoryVorKutaAcceptance of cookiesAcceptance of cookies

PHP Tutorial :: Strings (II)

PHP Example #8

Formatting text

Printf() function allows for a greater control than print() and uses a format rule to apply to elements to print. In the example, %.2f' is replaced by the value of $price and it is formatted to have two decimals (f indicates a float number).

<?php
$price = 5; $tax = 0.075;
printf('The dish costs $%.2f', $price * (1 + $tax));
print nl2br("\n\n");
$zip = '6520';
$month = 2;
$day = 6;
$year = 2007;
printf("ZIP is %05d and the date is %02d/%02d/%d", $zip, $month, $day, $year);
print nl2br("\n\n");
$min = -40;
$max = 40;
printf("The computer can operate between %+d and %+d degrees Celsius.", $min, $max);
print nl2br("\n\n");
print strtolower('Beef, CHICKEN, Pork, duCK');
print nl2br("\n");
print strtoupper('Beef, CHICKEN, Pork, duCK');
print nl2br("\n\n");
print ucwords(strtolower('JOHN FRANKENHEIMER'));
?>
The dish costs $5.38

ZIP is 06520 and the date is 02/06/2007

The computer can operate between -40 and +40 degrees Celsius.

beef, chicken, pork, duck
BEEF, CHICKEN, PORK, DUCK

John Frankenheimer

PHP Example #9

Substracting a string

With the substr() function we can extract a part of a string (a substring). Let's use this string as an example: The Fresh Fish with Rice Noodle was delicious, but I didn't like the Beef Tripe.

Here the form makes a call to an external script written into a .php file, whose source code can be seen below. The output will be displayed in a blank page, so hit Back to return to this webpage after seeing the result.

Your comments:
<?php
// Extracts the 30 first characters from $_POST['comments']
print substr($_POST['comments'], 0, 30);
// Adds suspension points
print '...';
?>

PHP Example #10

Substracting a string

In this example we will do the same, but starting by the end of the string. Write a credit card number and the function will return the four last digits. Write something like this: 4000-1234-5678-9101

Here the form makes a call to an external script written into a .php file, whose source code can be seen below. The output will be displayed in a blank page, so hit Back to return to this webpage after seeing the result.

Your card number:
<?php
print 'Card: XX';
print substr($_POST['card'], -4, 4);
?>

PHP Example #11

Replacing text

In this example we will replace part of a string with a different text.

Here the form makes a call to an external script written into a .php file, whose source code can be seen below. The output will be displayed in a blank page, so hit Back to return to this webpage after seeing the result.

Write a feminine name:
<?php
print str_replace('Anonymous', $_POST['replace'], 'This girl called Anonymous is so pretty!');
?>