问题描述
好的,这就是我要做的事情:我试图使用PHP开发本质上是markdown实现的 tiny 子集,而不是使用完整的markdown类.
Okay, here's what I'm trying to do: I'm trying to use PHP to develop what's essentially a tiny subset of a markdown implementation, not worth using a full markdown class.
我本质上需要做一个str_replace,但是每次出现针时都要替换替换字符串,以便处理打开和关闭HTML标记.
I need essentially do a str_replace, but alternate the replace string for every occurrence of the needle, so as to handle the opening and closing HTML tags.
例如,斜体是一对星号(如* this *),而代码块则由反引号(如"this")包围.
For example, italics are a pair of asterisks like *this*, and code blocks are surrounded by backticks like `this`.
我需要用对应的开头HTML标记替换第一次出现的两个字符对,然后用结束标记替换第二个字符.
I need to replace the first occurrence of a pair of the characters with the opening HTML tag corresponding, and the second with the closing tag.
关于如何执行此操作的任何想法?我发现会涉及某种正则表达式...
Any ideas on how to do this? I figured some sort of regular expression would be involved...
推荐答案
我个人将每次出现*
或\
的过程都用一个计数器循环,然后根据该字符用相应的HTML标记替换计数(例如,如果计数为偶数并且您打了星号,则将其替换为<em>
,如果它是奇数,则将其替换为</em>
,依此类推.)
Personally, I'd loop through each occurrence of *
or \
with a counter, and replace the character with the appropriate HTML tag based on the count (for example, if the count is even and you hit an asterisk, replace it with <em>
, if it's odd then replace it with </em>
, etc).
但是,如果您确定只需要支持几种简单的标记,则针对每种标记的正则表达式可能是最简单的解决方案.像这样的星号,例如(未经测试):
But if you're sure that you only need to support a couple simple kinds of markup, then a regular expression for each might be the easiest solution. Something like this for asterisks, for example (untested):
preg_replace('/\*([^*]+)\*/', '<em>\\1</em>', $text);
反斜杠也类似.
这篇关于PHP替换,但替换替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!