0

Im looking for an equivalent for str_split() in Smarty as {php}{/php} looks like deprecated and not very clean. I came across explode but it needs a delimiter and what I'm trying to get is:

1/2/3/4/5

from

$chars = str_split(12345);
foreach($chars as $char){
    echo $char . '/';
}

But in a Smarty environment. Any idea please?

David
  • 213
  • 3
  • 10

2 Answers2

1

Here is a regex based approach:

$chars = "12345";
$output = preg_replace("/(?<=\d)(?=\d)/", "/", $chars);
echo $output;  // 1/2/3/4/5
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • 1
    Nice one thanks! In a Smarty environment I got the job done with: {"12345"|regex_replace:"/(?<=\d)(?=\d)/":"/"} – David Jun 24 '21 at 08:39
  • I also needed to reproduce this with javascript like: `....replace(/(?<=\d)(?=\d)/, "/")` which works fine in Chrome and Firefox but not in Safari because of lookbehind not being supported that browser yet. Any better idea for js ? – David Jun 25 '21 at 15:19
  • @David For JS use a capture group: `str.replace(/(\d)(?=\d)/, "$1.")` – Tim Biegeleisen Jun 26 '21 at 00:40
0

You can user function .replace in JS pls check the following sample:

var text = '1 2 3 4 5', text = text.replace(/\s+/g, '/'); document.getElementById("demo").innerHTML =text;