Changes

Working with Strings and Text in PHP

1,880 bytes added, 10:50, 4 June 2007
no edit summary
Given that PHP is essentially a vehicle for the deployment of web content, and that much web content is text based, it should come as no surprise that PHP includes a range of features designed to ease the task of manipulating text and strings.
 
In this chapter we will explore a number of the functions and techniques provided by PHP to enable you, as a web developer, to perform tasks such as changing the case of a string, replacing one part of a piece of text with another peice of text, searching text and much more.
 
== Changing the Case of a PHP String ==
 
PHP provides a number of functions that enable changes to be made to the case of text contained in a string. These functions all take the string to be modified as an argument and return the modifed string. It is important to note that these functions are ''nondestructive'', that is to say they do not make any change to the original string, they simply return a completely new string containing the modification leaving the orignal string unaltered. The returned string can be assigned to a new variable or used directly in another function (such as a ''print'' or ''echo''):
 
<pre>
<?php
$myString = "This is a test string.";
 
$newString = strtoupper($myString); // Assign converted string to a new variable
 
echo strtolower($myString); // Use retruned string in a eacho statement
?>
</pre>
 
If a change to the original string is required (as opposed to assigning the modified version to a new variable) the returned string can simply be assigned to the original variable:
 
<pre>
<?php
$myString = "This is a test string.";
 
$myString = strtoupper($myString); // Assign converted string to the orignal variable
 
?>
</pre>
 
The PHP string functions designed to change the case of a string are listed below with descriptions:
 
* '''strtolower()''' - Converts entire string to lowercase
 
* '''strtoupper()''' - Converts entire string to uppercase
 
* '''ucfirst()''' - Converts the first letter of the sentence to uppercase
 
* '''ucwords()''' - Converts the first letter of every word to uppercase
 
=== Converting to and from ASCII Values ===