且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP替换,但替换替换字符串

更新时间:2023-02-18 20:03:05

我个人将每次出现*\的过程都用一个计数器循环,然后根据该字符用相应的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);

反斜杠也类似.