1

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..

zuk1
  • 18,009
  • 21
  • 59
  • 63
  • 1
    regular expressions are your friend. if only I knew more about them I could actually answer the question. – Brian Ramsay Jul 29 '09 at 13:18
  • There are solutions ... but a bit of info that might be helpful: how do you know which instances you want? Is it always the same? Reminds me of http://en.wikipedia.org/wiki/One-time_pad. – Smandoli Jul 29 '09 at 13:34

3 Answers3

1

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.
  • 3,648
  • 2
  • 26
  • 30
0

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

Community
  • 1
  • 1
brianng
  • 5,790
  • 1
  • 32
  • 23
0

Since you said you wanted to be able to define which instances should be highlighted and it sounds like that will be arbitrary, something like this should do the trick:


// Define which instances of a word you want highlighted
$wordCountsToHighlight = array(1, 2, 4, 6);
// Split up the paragraph into an array of words
$wordsInParagraph = explode(' ', $paragraph);
// Initialize our count
$wordCount = 0;
// Find out the maximum count (because we can stop our loop after we find this one)
$maxCount = max($wordCountsToHighlight);
// Here's the word we're looking for
$wordToFind = 'example'
// Go through each word
foreach ($wordsInParagraph as $key => $word) {
   if ($word == $wordToFind) {
      // If we find the word, up our count. 
      $wordCount++;
      // If this count is one of the ones we want replaced, do it
      if (in_array($wordCount, $wordCountsToHighlight)) {
         $wordsInParagragh[$key] = '<strong>example</strong>';
      }
      // If this is equal to the maximum number of replacements, we are done
      if ($wordCount == $maxCount) {
         break;
      }
   }
}
// Put our paragraph back together
$newParagraph = implode(' ', $wordsInParagraph);
It's not pretty and probably isn't the quickest solution, but it'll work.