Replace First Occurrence of String With PHP

How to replace the first occurrence of a string using substr_replace or preg_replace; using the string functions to perform drop-in replacements is recommended.

16180 views

Edited: 2020-12-26 18:31

In PHP, sometimes you might want to replace the first occurrence of a string. To do this you can use the preg_replace function to do a regular expression replace; however, due to difficulties with escaping backslashes it is safer to use substr_replace, and it is also more useful when you just need to do a drop-in replacement and do not need RegEx features.

The problem with backslashes exists both in the regular expression pattern, as well as the replacement string. This is important to keep in mind if you chose to use a RegEx. In addition, you will also need to escape literal backslashes that are defined inside variables of your PHP code. There are also other special characters that needs to be escaped, but those are exclusive to the pattern. Overall, these issues makes it very confusing to work with regular expressions where backslashes might occur in the strings.

It is recommended to use substr_replace for simple drop-in replacements. To do that, you can create your own function which you can use wherever needed. The below function will return the modified string on success, and the original string on failure:

function replace_first_str($search_str, $replacement_str, $src_str){
  return (false !== ($pos = strpos($src_str, $search_str))) ? substr_replace($src_str, $replacement_str, $pos, strlen($search_str)) : $src_str;
}

Usage:

$src_str = 'one, one, zero';
echo replace_first_str('one', 'two', $src_str);

Output:

two, one, zero

Replace first occurrence with 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 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 causes the function to only replace the first match – a value of 2 would replace the first two, 3 the first three, and so on.

Insert Ad unit before first section in page

To use a real-world example, let us try to insert an ad before the first subsection in the main content of a HTML page. Note that this assumes that you are using section elements to create your HTML sections, but you should easily be able to modify it to work with traditional h1-h6 elements.

A good position for ads in the content is at the top of subsections. To place an ad here, we can search for either h1-h6 or section elements, and then simply replace the first match we get with our ad code. Of course, we could insert an ad before all new sections, but that might clutter our page too much — so, please be aware of the negative effect that ads have on the user experience.

In the below example we will look for "<section" and replace it with <div>...</div><section; 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, while also allowing it to work with all HTML attributes. In order to do that, we leave out the tailing ">" from the opening element.

$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.

Links

  1. substr_replace - php.net
  2. preg_replace - php.net
  3. strings - php.net

Tell us what you think:

  1. In this Tutorial, it is shown how to redirect all HTTP requests to a index.php file using htaccess or Apache configuration files.
  2. How to create a router in PHP to handle different request types, paths, and request parameters.
  3. Tutorial on how to use proxy servers with cURL and PHP
  4. When using file_get_contents to perform HTTP requests, the server response headers is stored in a reserved variable after each successful request; we can iterate over this when we need to access individual response headers.
  5. How to effectively use variables within strings to insert bits of data where needed.

More in: PHP Tutorials