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.
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:
- Pattern
- Replacement
- Subject
- Limit
- 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
- substr_replace - php.net
- preg_replace - php.net
- strings - php.net
Tell us what you think: