String Replacer

Posted under » PHP on 01 April 2009

If you don't require regex, you should use str_replace to replace strings.

$link = str_replace("JScripts",'<a href="010.php">Javascript</a>',$word);

In the above example, any occurence of "JScripts" in the string ($word) will be replaced by a link to "010.php".

If you prefer case-insensitive replacement, use str_ireplace. In this example we want to replace carriage return or enter to html <br>

$html = str_ireplace("\r\n", "<br />",$textbox);

See also Array replacer.

However if regular expressions is needed use preg_replace.

$baong = "<option value=babi";
$pattern = "{<option value}";
$celeng = preg_replace($pattern, "<a href", $baong);

preg_replace() is sometimes known as ereg_replace()

You can also regular expressions and preg_match_all if you find regez useful.

However, if you find regular expressions daunting, use positioning and then substract those that you don't want..

Part 1

$pos = strpos($chunkotext, 'keystone');
// answer is perhaps 1110

Part 2

$eyedee = substr($chunkotext, 1120, -187);
// what is left  is perhaps needle

See also PHP implode and substact.

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data