Reza Nadimi
Reza Nadimi

Reputation: 65

How to get the second instance of repetitive word in regex?

My string is Add New Tax Rate,Add New Tax Rate.

I want to get the second instance of Tax with regex pattern in my string and replace it.

Upvotes: 1

Views: 42

Answers (1)

anubhava
anubhava

Reputation: 785186

Using PHP's PCRE feature you can use this regex to replace only 2nd instance of Tax:

$str = 'Add New Tax Rate,Add New Tax Rate';

$repl = preg_replace('/^.*?\bTax\b(*SKIP)(*F)|\bTax\b/', 'REPLACED', $str, 1);

//=> Add New Tax Rate,Add New REPLACED Rate

RegEx Demo

Here ^.*?\bTax\b(*SKIP)(*F) will match and skip first match of Tax.

Upvotes: 1

Related Questions