tags:

views:

126

answers:

3

Basically I have a variable which contains a few paragraphs of text and I have a variable which I want to make bold within the paragraphs. (By wrapping <strong></strong> tags around it). The problem is I don't want to make all instances of the word bold, or else I'd just do a str_replace(), I want to be able to wrap the first, second, fourth, whatever instance of this text in the tags, at my own discretion.

I've looked on Google for quite awhile but it's hard to find any results related to this, probably because of my wording..

A: 

You can probably reference 'Replacing the nth instance of a regex match in Javascript' and modify it to work for your needs.

brianng
+1  A: 

I guess that preg_replace() could do the trick for you. The following example should skip 2 instances of the word "foo" and highlight the third one:

preg_replace(
    '/((?:.*?foo.*?){2})(foo)/', 
    '\1<strong>\2</strong>', 
    'The foo foo fox jumps over the foo dog.'
);

(Sorry, I forgot two questionmarks to disable the greediness on my first post. I edited them in now.)

cg
A: