Reputation: 7754
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
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);
Upvotes: 2
Reputation: 3328
$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