zuk1
zuk1

Reputation: 18369

PHP Bolding The 'x' Instance of a Variable In a String

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

Upvotes: 1

Views: 234

Answers (3)

ilovebonnie.net
ilovebonnie.net

Reputation:

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.

Upvotes: 0

cg.
cg.

Reputation: 3678

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

Upvotes: 1

brianng
brianng

Reputation: 5820

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

Upvotes: 0

Related Questions