I want to replace only the first instance if two matches returned.
example:
$sen = "The quick brown fox jump over the lazy dog, fox is quick";
how can i match only the first fox and replace it with wolf and vice versa.
Output:
The quick brown wolf jump over the lazy dog, fox is quick
or:
The quick brown fox jump over the lazy dog, wolf is quick
Thanks.
Counting matches by using global option
/g, assign list of matches to an empty list to get a count (better than a temp variable). First replace is basic. Second uses a counter that increments for each match, and replaces at the proper time.Note use of word border
\bto prevent false matches, such asfirefox,foxy lady, etc.Code:
Output:
If you wish a more reusable code, you can make a subroutine out of it.
You could then even use the sub for both substitutions: