Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch off the g (global) modifier in preg_replace

Tags:

regex

php

The g (global) modifier is on by default in preg_replace PHP, how can it be switched off ?

If I do a preg_replace(/n/,'',$string); it will replace all occurrences of n but I want to replace only the first occurrence of n. How should I do it?

like image 902
aelor Avatar asked Jan 11 '23 20:01

aelor


1 Answers

Use the fourth parameter for preg_replace(). From the documentation:

limit — The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).

preg_replace('/n/', '', $string, 1);

But for something simple as this, a regex is overkill. A simple str_replace() should suffice:

$string = str_replace('n', '', $string, 1);
like image 164
2 revs Avatar answered Jan 26 '23 04:01

2 revs