Changes

Working with Strings and Text in PHP

102 bytes added, 19:15, 7 June 2007
no edit summary
== 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 original 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>
Those familar with other programming languages such as C and C++ will probably be familiar with the concept of formatting strings and the ''printf()'' function. The printf function allows strings to constructed which contain variables and provides a number of formatting options for those variables.
Essentially , printf allows you to specify a string and define how particular variables are to be embedded in that string. ''fprintf()'' takes two or more arguments and takes the the following form:
<tt>fprintf ( "String", variable1, variable2, ... );</tt>
The ''String'' represents the string that is to displayed and contains the formatting specifiers. The ''variables'' specify the variables that are to be substituted inplace in place of the respective formatting rules.
=== PHP printf formatting specifiers ===
<tt>My favorite color is Green and my lucky number is 12.</tt>
Suppose we wanted to display express our lucky number as a hexadecimal value(as all good software engineers do). All we would need to do is replace the %d with a %x:
<pre>
== Finding the Length of a PHP String ==
The length of a PHP string can be obtained using the ''strlen()'' function. The ''strlen()'' function takes the string to be measured as an argument and returns the length value:
<pre>
== Converting a String into a PHP Array ==
Any string in PHP can be converted into a PHP array (see the [[PHP Arrays]] chapter for an overview of arrays). This is achived the achieved using the PHP ''explode()'' function. The ''explode()'' function takes three arguments and returns an array:
* '''delimeter''' - the character that is to be used as the break point between array elements. For example a space character or a comma.
== Removing Leading and Trailing Whitespace from a PHP String ==
The leading and trailing whitespcae can be removed from a string using the PHP ''trim()'' function. Whitespace characters are defined by PHp PHP to be space, tab, newline, carriage return, NULL and vertical tab characters.
The ''trim()'' command takes the string to be trimmed as an argument and returns a modified version of the string. The function is non-destructive, in that it does not modify the original string.
The following exmaple example trims the whitespace from the specified string:
<pre>
== Searching for Characters and Substrings in a PHP String ==
PHP provides the ability to find the position of a specified sequence of characters (better known as a ''substring'') within a string via the ''strpos()'' and ''strrpos()'' functions.
The ''strpos()'' function finds the first occurence occurance a substring and takes two mandatory and one optional argument. The first argument is the string in which the search should be performed, and the second the substring for which to search. The optional third argument tells PHP the point in the string to initiate the search. The function returns boolean false (0) if no match is found, otherwise it returns the index into the string of the occurence.
Note that if a string begins with the substring there will be some confusion since the function will return 0, which could equally be interpreted as a failure to find a match. The key point to understand here is that a failure to find a match will return a boolean zero. A match starting at position zero will return a numeric 0. To resolve this issue it is best to ensure that you are comparing like variable types. You may recall from the [[PHP Operators]] chapter about comparing variables to ensure they are of the same type ''and'' value using the === and !== operators. We can use this technique to vefify we are getting boolean false, and not an integer 0:
</pre>
Similarly, the ''strrpos ()'' function returns the position of the last occurance of the substring.
== Extracting and Replacing Substrings in PHP ==
A sub-section of any PHP string can be extracted and replaced using the ''substr)('' and ''substr_replace()'' functions.
The ''substr()'' function takes two arguments which represent the source string and the start index. An optional third argument specifies the length of the substring (if no length is specified the end of the string is assumed). The function retruns returns the requested substring:
<pre>
The above example will extract the word ''cat'' from the string.
The ''substr_replace ()'' function takes up to four arguments. The first is the source string on which the replace is to be performed. The second argument is the replacement string. The third specifies the index offset of the start of the replacement. The optional fourth argument defines number of characters from tyhe the offset point to include in the replacement (useful if your replacement text is shorter than the original text being replaced).
We can now extend our example to replace some text in our string:
<tt>New String = There is a dog in the tree.</tt>
It is perfectly valid to replace one substring with another of different length. It is also possible to simply remove a substring by simply passing in an empty replacement string to the ''substr_replace ()'' fucntion.
== Replacing All Instances of a Word in a PHP String ==
All the instances of a word in a string can be replaced using the PHP ''str_replace()'' function. ''str_replace()'' takes 3 required and one optional argument. The first argument represents the string to be replaced, the second the replacement value and the third the target string. The optional fourth argument is a reference to a variable where the results of the repalcement replacement will be stored for subsequent inspection.
A simple example is as follows:
<tt>New String = There was a dog in the car, and I think it was my dog!</tt>
A case insensitive search and replace can similarly be performed using the ''eregi_replace()'' function which takes the same arguments as ''str_replace()''