Blade
Blade

Reputation: 51

match pattern and replace with count in PHP

How would I go about getting a count of a pattern match then replace the pattern with the count.

The patterns I am trying to match all are bbcode style tags in a string.

for example: This is a paragraph of [blue]text[/blue] where all the words are of a [blue]color[/blue].

I need to replace each tag with a number and additional text as it occurs, like [@@1@@] and [@@2@@]

I know I can match the pattern with preg_match('/[blue](.*?)[/blue]/i',$string) or even replace preg_replace

But how can I get use either of those functions to get a count then replace the match with the it's count position?

Upvotes: 1

Views: 465

Answers (2)

lupatus
lupatus

Reputation: 4248

Try preg_replace_callback:

$result = preg_replace_callback('/(\[blue\])([\[]*)(\[\/blue\])/i', function ($matches) {
    static $incr = 0;
    ++$incr;
    return '[@@'.$incr.'@@]'.$matches[2].'[@@'.$incr.'@@]';
}, $text);

see manual for more info on that

Upvotes: 1

JDuarteDJ
JDuarteDJ

Reputation: 1104

You can use the $matches param.

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

if you pass $matches it will return an array with all the results. use count($matches) to return the count!

EDIT: After you get the $matches array you can replace them using the array's key as the count value.

foreach($matches as $k=>$mat){
preg_replace ( /*same pattern*/,"[@@".$k."@@]", /* same subject */,1); //fourth param is to replace only one!
}

try this!

EDIT2: correct is preg_replace not preg_match (in my EDIT).

Upvotes: 1

Related Questions