Preg Replace-替换匹配项的第二次出现 [英] Preg Replace - replace second occurance of a match

查看:279
本文介绍了Preg Replace-替换匹配项的第二次出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对php来说还比较陌生,希望有人可以帮我替换正则表达式,或者不确定我是否可以匹配替换.

I am relatively new to php, and hope someone can help me with a replace regex, or maybe a match replace I am not exactly sure.

我想自动将(比赛的第二次出现)加粗,然后使比赛的第4次显示为斜体,然后使比赛的第7次显示为下划线.

I want to automatically bold the (second occurance of a match) and then make the 4th appearance of a match italic and then the 7th appearance of a match underlined.

这基本上是出于内容搜索引擎优化的目的.

This is basically for SEO purposes in content.

我已经用:做过一些替换,并且认为这应该可以解决问题吗?

I have done some replacements with: and were thinking this should do the trick?

preg_replace( pattern, replacement, subject [, limit ])

我已经知道我想在

'pattern' is also a word that is already defined like [word].
`replacement` 'This is a variable I am getting from a mysql db.
'subject' - The subject is text from a db.

让我说我有这个内容:这或多或少地解释了我想做的事.

Lets say I have this content: This explains more or less what I want to do.

这是我要替换的文本示例.在本文中,我想第二次出现 example <大胆的.然后,我想跳过下一次在文本中出现示例的情况,并使单词 example 第4次以斜体显示.然后,我想跳过单词示例在文本中出现的第5次,还有第6次,最后要跳过第7次, example 出现在其下划线的文本中.在此示例中,我已使用超链接作为下划线示例,因为在文本编辑器中未看到下划线功能.示例一词在文本中可能会出现更多次,但是我唯一需要的是下划线一次,一次加粗一次,斜体一次.以后我可能还会在示例"一词上加上一些引号,但这还不是优先事项.

This is an example of the text that I want to replace. In this text I want to make the second occurance of the word example < bold. Then I want to skip the next time example occurs in the text, and make the 4th time the word example appears in italic. Then I want to skip the 5th time the word example appears in the text, as well as the 6th time and lastly wants to make the 7th time example appears in the text underline it. In this example I have used a hyperlink as the underline example as I do not see an underline function in the text editor. The word example may appear more times in the text, but my only requerement is to underline once, make bold once and make italic once. I may later descide to do some quotes on the word "example" as well but it is not yet priority.

同样重要的是,如果该单词出现的次数不少于7次,则代码不要出错.

It is also important for the code not to through an error if there is not atleast 7 occurances of the word.

我将如何做到这一点,任何想法都将不胜感激.

How would I do this, any ideas would be appreciated.

推荐答案

您可以使用 preg_split 进行拆分比赛中的文字,进行修改,然后将所有内容放回原处:

You could use preg_split to split the text at the matches, apply the modifications, and then put everything back together:

$parts = preg_split('/(example)/', $str, 7, PREG_SPLIT_DELIM_CAPTURE);
if (isset($parts[3])) $parts[3] = '<b>'.$parts[3].'</b>';
if (isset($parts[7])) $parts[7] = '<i>'.$parts[7].'</i>';
if (isset($parts[13])) $parts[13] = '<u>'.$parts[13].'</u>';
$str = implode('', $parts);

第i个匹配项的索引公式为 index = i ·2-1.

The index formula for the i-th match is index = i · 2 - 1.

这篇关于Preg Replace-替换匹配项的第二次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆