1

I'd like to replace a string like 0001 with " 1" with 3 spaces.

I've tried str_replace but that doesn't work on 0010. I've tried some preg_replace but can't get the replacement right to replace the same number

I've written this basic thing and it works, but am looking for something more efficient if possible.

$pin = '0010';
$temp = ltrim($pin, '0');
$spaces = strlen($pin) - strlen($temp);
for ($x=1;$x<=$spaces;$x++) $temp = ' '.$temp;
echo $temp;

Closest I got with preg_replace was this but I'm not sure what to do with replacement:

preg_replace('/0+/', ' ', $pin)
Andrew T
  • 367
  • 2
  • 14
  • Is efficiency of huge importance because you are performing this zero replacement on hundreds of thousands of strings in a single execution? – mickmackusa Jun 26 '20 at 16:11

3 Answers3

2

\G for the win!

https://www.regular-expressions.info/continue.html

\G will match the start of the string and continue to match until it can't.

What is the use of '\G' anchor in regex?

Match a zero from the start of the string, then match every following zero one-at-a-time. Replace every matched zero with a space.

Code: (Demo)

$pin = '0010';
var_export(preg_replace('~\G0~', ' ', $pin));

Output:

'  10'
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
0

I don't see how to do this any easier with a regular expression, but you could make your other code more concise by using str_repeat:

$pin = '0010';
$temp = ltrim($pin, '0');
$spaces = strlen($pin) - strlen($temp);
$new_pin = str_repeat(' ', $spaces) . $temp;
echo $new_pin;
zeterain
  • 1,140
  • 1
  • 10
  • 15
  • You could combine some of these statements to make fewer lines of code, but I believe this will be more readable. I always prefer readable code to clever code. – zeterain Jun 26 '20 at 15:32
0

You said:

but am looking for something more efficient if possible

  • First, note that a one-liner isn't necessarily efficient(as you tried for preg_replace() and regex is actually a bit slower since it gets compiled first).
  • Second, you can better adopt for just a 2 pass approach over the string. This also edits the string in-place without extra string variables which is desirable in your case.

Snippet:

<?php

$str = '000010';
$len = strlen($str);

for($i = 0; $i < $len; ++$i){
    if($str[$i] == '0'){
        $str[$i] = ' ';
    }else{
        break;
    }
}

echo $str;
nice_dev
  • 17,053
  • 2
  • 21
  • 35