1

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

php love
  • 13
  • 4

4 Answers4

1

If you dont know the position of "#", use this :

$pos=strpos($withoutP, "#");
$withP = substr_replace($withoutP, 'P', $pos, 0);
Basto
  • 216
  • 1
  • 5
0

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;
Daan
  • 12,099
  • 6
  • 34
  • 51
  • thanks for your response , but i have some issue , i can't assume that the string has always the word 'Order ' it can be in French with 'Commande' , so is there any idea to test just on the number "#000000022" , for example using the explode and implode functions – php love Jun 25 '21 at 12:04
  • Yes, absolutely, I've added an example. – Daan Jun 25 '21 at 12:11
0
<?php echo substr_replace($oldstr, 'P', 7, 0); ?>

taken from: Insert string at specified position

0

You can use str_replace function

function addP($text) {
   return str_replace('Order #', 'Order #P', $text);
}