基本上我有一个包含几段文字的变量,我有一个变量,我想在段落中加粗。 (通过在其周围包裹<strong></strong>
标签)。问题是我不想让这个单词的所有实例都是粗体,否则我只是做一个str_replace(),我希望能够包装第一个,第二个,第四个,这个文本的任何实例。标签,由我自行决定。
我在谷歌上看了很长一段时间,但很难找到与此相关的任何结果,可能是因为我的措辞......
答案 0 :(得分:1)
我想preg_replace()
可以为你做到这一点。以下示例应跳过单词“foo”的2个实例,并突出显示第三个:
preg_replace(
'/((?:.*?foo.*?){2})(foo)/',
'\1<strong>\2</strong>',
'The foo foo fox jumps over the foo dog.'
);
(抱歉,我在第一篇文章中忘了两个问号来禁用贪婪。我现在编辑了它们。)
答案 1 :(得分:0)
您可以引用“Replacing the nth instance of a regex match in Javascript”并对其进行修改以满足您的需求。
答案 2 :(得分:0)
既然你说你想要能够定义哪些实例应该被突出显示并且听起来像是任意的,那么这样的事情应该可以解决问题:
// 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);
它不漂亮,可能不是最快的解决方案,但它会起作用。