By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Replace First Occurrence of String With PHP

How to replace the first occurrence in a string. Tutorial on how to replace the first match in a string with PHP.

Edited: 2014-12-28 04:31

Sometimes you might want to replace the first occurrence of a string, in PHP this can be done with a simple preg_replace. The php preg_replace function allows you to perform a regular expression based search and replace inside of strings, it accepts 5 parameters listed below:

  1. Pattern
  2. Replacement
  3. Subject
  4. Limit
  5. Count

The first parameter is the pattern to be matched, the second is the replacement to replace the found matches with. The third is the subject, aka the source string to search in. The fourth and final parameter is known as the limit parameter, we can use this to limit the number of replacements performed. The last parameter, known as the count parameter, contains the number of replacements – this is not relevant in this tutorial, as we will only be replacing the first occurrence in the string.

The below is a simple example of how to replace the first matching: abcde in a string:

$Replacement = 'edcba';
$Source = '1234 abcdefg 1234 abcdefg 1234 abcdefg';
echo preg_replace('/abcde/', $Replacement, $Source, 1);

The limit parameter tells PHP only to replace the first match – a value of 2 would replace the first two, and 3 the first three – and so on.

Insert Ad unit before first section in page

The below example shows how to replace the first occurrence of the string: <section – this is the opening tag of a new HTML section – the point of replacing this, is to place a content ad before the first subsection in a page. Consider the below example:

  $Ad_Unit = '<div>This is a placeholder division element for a Ad unit</div><section';
  $HTML_Source = '                <p>Just a paragraph</p>
                  <h1>Header of first subsection</h1>
                  ....The Rest of the HTML source.....';

  echo preg_replace('/<section/', $Ad_Unit, $HTML_Source, 1);