| Search and Replacement |
| Article Index |
|---|
| Search and Replacement |
| Page 2 |
| Page 3 |
| Page 4 |
Using strings without being able to tell what's inside them is a bit like driving around at night with your headlights offyou know the road might be there, but you can't really tell.
PHP offers a wide array of functions for searching and replacing text inside strings using both the traditional "match and replace" approach and a special system known as regular expressions, which we will examine later in this book.
The simplest form of search consists of looking for a substring inside a string. This task is usually performed through a call to strpos($haystack, $needle[, $start]), which returns false if $needle cannot be found inside $haystack, or returns the position of $needle's first character inside $haystack otherwise. If the integer parameter $start is specified, the search operation is performed starting from the character in $haystack whose position corresponds to the value of $start.
For example, the following script will return String found at position 22:
<?php
$haystack = 'Three merry men and a bottle of wine';
$pos = strpos ($haystack, 'bottle');
if ($pos === false)
echo "String not found\n";
else
echo "String found at position $pos\n";
?>
There is one very important detail to notice in the previous script. To determine whether the call to strpos() did indeed succeed and a match for the substring bottle was found inside $haystack, the value of $pos is compared to false using the type-checking operator ===. The reason for this is that the Boolean value false is equivalent to the integer value zero. However, strpos() will return zero if $needle is found starting from the first character of $haystack. Therefore, simply checking the return value of a call to strpos() using an expression like
if (!strpos ($haystack, $needle))
die ("Failure");
| Users' Comments (0) |
|
No comment posted








