Online
 
Thursday, 20 November 2008
 
 

Search and Replacement | Print |  E-Mail
 

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");


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

Rokok Kretek Jumbo Coklat

“Terbuat dari tembakau, saos dan cengkeh pilihan kwalitas tinggi sehingga menghasilkan rokok dengan rasa yang cocok untuk segala cuaca”
Jumbo Coklat - Powered By G-Ads

 
Top! Top!