Visit the Official PHP Website

Search this Site

PHP Programming

By James N Hitz

The preg_replace() function

preg_replace() works in a manner almost similar to that used by the preg_match() function we have just discussed. The difference is in the application and syntax (which actually means the two functions are completely different) ;)

preg_replace() finds an occurence of a given pattern inside and string and replaces it (changes it to) another pattern. Think of it like you would think of the "Find and Replace" function in your word processor. The syntax for using the preg_replace() function is:

preg_replace("find_pattern", "replace_pattern", "subject_string");

Let's take an example. In our example we will grab data from a textarea form control and convert all enters marks (carriage returns) (\n) into <p> tags. This code assumes the textarea has a name atribute "comments" and there creates a variable named $comments:

preg_replace("\n","<p>",$comments);

This will replace all carriage returns (enters) into <p> tags - even multiple enters will become multiple <p> tags. To avoid this we could code:

preg_replace("\n{1,}","<p>",$comments);

This tests for one or more occurences of the enter mark - \n{1,} and changes it to only one P tag.

In this example we have also added 'i'. As earlier said, 'i' means ignore case. With this alone, only the first instance will be changed. 'g' which means global will effect the replacement throughout the string named $comments and not only the first occurence.

<< The preg_match function | The preg_split function >>

JamHitz Productions