-1

I have this sentence:

piece:5,dozen:10

and I need to print it via php like this:

piece:5$,dozen:10$

without editing the line in the editor, I need php to do it automatically. Now I thought to split it like this:

$uom = "piece:5,dozen:10";
$lst1 = explode(',', $uom);
var_dump($lst1);

and it returned like this:

array (size=2)

0 => string 'piece:5' (length=7)

1 => string 'dozen:10' (length=8)

which is ok for now, so I need after each string piece:5$ dozen:10$ and then I did this:

$lst2 = implode('$ ', $lst1);
echo $lst2;

It printed:

piece:5$ dozen:10

I need the $ to be printed also after 10, so it will be like this:

piece:5$ dozen:10$

What is the right way to do this? What did I do wrong? What if the values are dynamically coming from the database?

Progman
  • 14,690
  • 4
  • 32
  • 46
DBblack
  • 23
  • 5

2 Answers2

0

You can use a combination of explode, array_map and implode like so:

<?php

$uom = 'piece:5,dozen:10';

$add_dollars = array_map(function($e) {
    return $e . '$';
}, explode(',', $uom));

echo implode(" ", $add_dollars);
Jacob Mulquin
  • 2,486
  • 1
  • 17
  • 22
0

I see few explode-implode answers. I don't want to duplicate answer, so let me do it another way – with regex.

$data = "piece:5,dozen:10";
echo preg_replace("/(\d+)/i", "$1\$", $data);

It may be a good idea to make it a bit more complex, i.e. take not only \d+, but also previous string and colon. Rather without(!) comma. In my opinion this may be better (because it's usually worth to be strict in regex):

$data = "piece:5,dozen:10";
echo preg_replace("/([a-zA-Z]:\d+)/i", "$1\$", $data); 

I encourage you to read php manual: preg_replace.


Answering also the question about jQuery – you don't need to use jQuery, you can do that in pure javascript. And it will be really similar! For example:

let data = "piece:5,dozen:10";
let modified = data.replace(/([a-zAZ]:\d+)/g,"$1\$");
console.log(modified);
Sylogista
  • 480
  • 3
  • 9