You should now be able to append, prepend, or join the strings at any other position you like. In this quick tip, I have covered different scenarios for concatenating strings in PHP. Adding the word length to our initial index gives us the correct position to concatenate the substring at the end of a particular word. When adding substrings at the end of words, we also need to take the length of words into account. This makes it easier for us to concatenate the substring at the beginning of a particular word. The strpos() function gives us the position of the first character of our substring inside the main string. This is because the position of our word will probably be different in each string, and we need to adjust the value of the index accordingly.
The big difference here is that we have moved the $index variable inside our loop. Here is an example of concatenating strings before a particular word. It simply finds the position of our $needle string inside the main text block or $haystack. The strpos($haystack, $needle) function is perfect for this purpose. The only extra step we need to take is to figure out the index. Concatenating Strings Before or After a Particular WordĬoncatenating a string before or after a particular word works just like joining strings at a particular index. In the above code, the value of the $index variable is simply the position at which we would like to concatenate our substring inside the main string. We can use the substr() function in PHP to split the main string in two parts at the desired index and then join the parts back together with our string in the middle. Concatenating Strings at a Particular Index We will cover both these situations in this section. These are splitting the main string at a particular index, or splitting the main string after a particular word. There are two common cases when you need to join strings at some place other than the beginning or the end of a string. Here is an example that prepends different strings to a name in PHP: Concatenating Strings at a Particular Point
Here is an example which shows how to append strings in PHP: It is a shorter way of appending the argument on the right side to the argument on the left side. = if you want to join the strings and assign the result to the same variable.