Skip to content
Advertisement

how to add a specific letter in a specific word in php

Hello everyone I am new on PHP, in my case I want to add a specific letter in a specific word in the sentence.

For example :

I have a function that returns this string in html => “Order #00000001000” , I want to add a letter “P” after the “#” like this => “Order #P00000001000”,

PS : I don’t want to change it in the function, I just want to change it in the HTML directly

Advertisement

Answer

You can use substr_replace. The code below says: on the 7th place of string $withoutP insert the letter P.

<?php
$withoutP = "Order #000000022";
$withP = substr_replace($withoutP, 'P', 7, 0);

echo $withP;

If you can’t assume the string always has the word Order in it, you can use a combination of implode, explode and substr_replace.

<?php
$withoutP = "Order #000000022";
$exploded = explode("#", $withoutP);
$exploded[1] = substr_replace($exploded[1], 'P', 0, 0);

$withP =  implode("#", $exploded);
echo $withP;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement