mahen3d
mahen3d

Reputation: 7754

PHP preg_replace with consecutive number of times depending on the match?

I have strings like below in a php string, which i want to replace with tabs characters depending on the value after the [(number of times tab will appear)) ...]

[4m ljjklj klj lkj lkjlj lk[]
[3m ljjklj klj lkj lkjlj lk[]
[m ljjklj klj lkj lkjlj ljk l

i have written the following code

$string_log=  preg_replace('/\[(.*?)m/',"\t",$string_log);

which replaces with one tab character, however i need to replace it with depending on the number in-front of the letter m .

for example if the string is

[4m] then it should be \t\t\t\t
[m] then it should be \t
[2m] then it should be \t\t

how can achieve this in php with preg_replace ?

Upvotes: 2

Views: 766

Answers (2)

hwnd
hwnd

Reputation: 70732

You want to use a callback to achieve this.

$str = preg_replace_callback('~\[(\d*)m~', 
     function($m) {
         $count = $m[1] ?: 1;
         return str_repeat("\t", $count);
      }, $str);

Code Demo

Upvotes: 2

Austin
Austin

Reputation: 3328

Use preg_replace_callback:

$string_log = preg_replace_callback('/\[(.*?)m/', function ($match) {
    if ($match[1]) $count = $match[1];
    else $count = 1;
    return str_repeat("\t", $count);
}, $string_log);

If you have to use plain preg_replace and can't use another function, then I think you will have to use the /e modifier to execute code for each match, which is very dangerous and should be avoided.

Upvotes: 3

Related Questions