Last Updated: July 06, 2022
·
72.25K
· dfeddad

Simple way to insert a string into another string at any position in PHP

If you want a very simple and short solution to insert string into another string use:
substr_replace ( $string , $replacement , $start , 0 ). The key here is zero, and because we set $length to zero this function will have the effect of inserting the replacement into the string.

<?php

$string = 'I am happy today.';
$replacement = 'very ';

echo substr_replace($string, $replacement, 4, 0); // I am very happy today.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

PHP applications still send a browser full of JavaScript. Hardening the server does not inventory the payment, analytics, and plugin scripts that run after the HTML is delivered.

Security insights from Cside