Online
 
Friday, 09 January 2009
 
 
More article:
Related Content:

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:


Tags: Add more tags...,
This entry was posted on . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a comment. Tags: Simple PHP, Pear, Easy PHP, PHP Tutorial, PHP MySQL, XSLT, Sap Tutorial, CSS Tutorial, XSL FO Java, SQL Tutorial.
Users' Comments (0)

Comment an article
  Name
  E-mail
   Title
Available characters: 4000
 Notify me of follow-up comments
This image contains a scrambled text, it is using a combination of colors, font size, background, angle in order to disallow computer to automate reading. You will have to reproduce it to post on my homepage
Enter what you see:

No comment posted

Cool Graphic Wallpaper 7
Statistic


Last Post

 
Top! Top!