Changes

Working with Strings and Text in PHP

1,550 bytes added, 16:52, 4 June 2007
Searching for Characters and Substrings
<tt>Before change = aBcdefghijklmn</tt><br>
== 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 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><?phpif (strpos("Hello World", "Hello") !== false) echo 'Match found';?></pre> Similarly, the strrpos function returns the position of the last occurance of the substring. == Extracting and Replacing Substrings in PHP ==