Speed up development with full-stack environments for every branch.

Learn More

Case insensitive string replacement using eregi_replace() function

8 Runs 56 Views 12 Copies
Saved

Saved

<?php

/**
 *  string replacement using eregi_replace
 * 
 */
echo '<center>';
echo '<b><u>ereg_replace() function usage <br />(tony is not replaced because the pattern searched
is Tony and the function is case sensitive):</u></b><br />';
//code block with ereg_replace
//array where the keys are string to be replaced and the values are the replacements
$replacementStrings = array('little' => 'big', 'John' => 'Michael', 'Tony' => 'Dale');
//this patters means any string but not one in the list so in our case any character 
//that is not a letter or a digit
$stringToReplace = 'John is the best friend of tony';
//keeping a record of the initial string because it will be modified and we need to display it at the end
$stringToReplaceinitial = $stringToReplace;

foreach ($replacementStrings as $toBeReplaced => $replacement) {
    //replacing the indexes of the array with the values
    $newString = ereg_replace($toBeReplaced, $replacement, $stringToReplace);
    $stringToReplace = $newString;
}
echo '<br /><div style="background-color:red;color:#fff;padding:10px;width:400px;font-size:16px">
The old string: ' . $stringToReplaceinitial . '<br /><br />The new string: ' . $newString . '
</div><br />';


//code block with eregi_replace
//array where the keys are string to be replaced and the values are the replacements
echo '<b><u>eregi_replace() function usage <br />(tony is now replaced because the pattern searched is Tony and the function is case insensitive) :</u></b><br />';
$replacementStrings = array('little' => 'big', 'John' => 'Michael', 'Tony' => 'Dale');
//this patters means any string but not one in the list so in our case any character that 
//is not a letter or a digit
$stringToReplace = 'John is the best friend of tony';
//keeping a record of the initial string because it will be modified and we need to display it at the end
$stringToReplaceinitial = $stringToReplace;

foreach ($replacementStrings as $toBeReplaced => $replacement) {
    //replacing the indexes of the array with the values
    $newString = eregi_replace($toBeReplaced, $replacement, $stringToReplace);
    $stringToReplace = $newString;
}
echo '<br /><div style="background-color:green;color:#fff;padding:10px;width:400px;font-size:16px">
The old string: ' . $stringToReplaceinitial . '<br /><br />The new string: ' . $newString . '
</div><br />';

echo '</center>';
?>
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).