| Search and Replacement |
| Article Index |
|---|
| Search and Replacement |
| Page 2 |
| Page 3 |
| Page 4 |
<?php
$haystack = 'Three merry men';
$pos = strstr ($haystack, 'merry');
if (!$pos)
echo "String not found\n";
else
echo "String found: $pos\n";
?>
Replacing Strings
PHP provides two main functions for performing simple search-and-replace operations. The first one is substr_replace, which can be used whenever you know the location of the substring that must be replaced and its length. For example:
<?php
$haystack = 'Three merry men';
$newstr = substr_replace ($haystack, 'sad', 6, 5);
echo "$newstr\n";
?>
The preceding script will return Three sad men. The substr_replace function works essentially by cutting out the substring of $haystack delimited by the third (start) and optional fourth (length) parameters, and then replaces it with the string passed to it in the second parameter.
Naturally, you do not always have the luxury of knowing exactly where the substrings to be replaced are in your haystack string; indeed, there might be more than one string that needs to be replaced. In these cases, you can use the str_replace function, which combines the search capabilities of strstr() with the replace functionality of substr_replace.
The syntax of str_replace() is as follows:
| Users' Comments (0) |
|
No comment posted








