Thursday, October 7, 2010

Search and replace of exact matching string in PHP

If you have to make and exact search, use preg_replace function with simple regular expression pattern. This function is used to search and replace a string according to the pattern provided.
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
mixed = any type of data, from  string to array.
array to array replace, string to string replace.
If your pattern doesn't contain regular expression, and you are going to search and replace string, please use str_replace function instead.
$replacement is the new string that will substitute the string or array following the pattern.
$subject is the array or string in which search and replace operation performs.

To make exact match, you have to use \b in both sides of the pattern.
For example, 
$pattern="/\bpatternstring\b/"; or
$pattern="/\b[0-9a-zA-Z]+\b/";
If you have to escape any special characters, then use \ (backslash) before that character.
$pattern="/\bxyz\[\]pqrs\b/";
If you have to make the search irrespective of case, need to use i , if in your subject includes utf-8 characters, use u,in the pattern.
 $pattern="/\bxyz\[\]pqrs\b/iu";

No comments:

Post a Comment

Thanks for your valuable comments.

Important queries based formulas to watch performance of a MySQL based application

(1) Session Vs global status variables value select G.variable_name,G.variable_value GlobalValue,S.variable_value SessionValue from (selec...