By using this site you agree to the use of cookies.

Learn more

Share via:

Replace First Occurrence of String With PHP

How to replace the first match only using preg_replace.

Edited: 2017-03-26 16:17

In PHP, sometimes you might want to replace the first occurrence of a string. To do this, you can perform a sumple preg_replace.

The preg_replace function allows you to perform a regular expression based search and replace inside of strings. The function accepts 5 parameters, listed below:

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

The first parameter,the pattern to be matched

The second is the replacement string.

The third is the subject, (aka the source string to search in).

The fourth 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 for tutorial, as we will only be replacing the first occurrence in the string.

Replace first occurrence

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 causes the function to only 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

A good position for ads in the content is at the top of subsections. To do this, we can search for either h1-h6 or section elements, and then simply replace the first match we get with our ad code, while we also fix the section.

In the below example we will look for "<section" and replace it with

this is the opening tag of a new HTML section. The reason for replacing this, is that we want the ad before the first subsection in the content.

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

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

The $HTML_Source variable is just an example, the contents of this variable can be fetched from your database.

The $Ad_Unit variable can be filled with your ad code. If you are using Adsense, then you should fill it with the code from Adsense.