【问题标题】:PHP preg_replace markdown issue - detecting duplicatesPHP preg_replace markdown 问题 - 检测重复项
【发布时间】:2023-04-06 08:57:01
【问题描述】:

在我正在构建的项目中,我想按如下方式使用降价

*text* = <em>text</em>
**text** = <strong>text</strong>
***text*** = <strong><em>text</em><strong>

由于这是我需要的仅有的三种 markdown 格式,我希望保持轻量级并避免导入整个 PHP markdown 库,因为这会引入我不需要的功能并产生问题。

所以我一直在尝试构建一些简单的正则表达式替换。使用 preg_replace 我运行:

'/(\*\*\*)(.*?)\1/' to '<strong><em>\2</em></strong>'

'/(\*\*)(.*?)\1/' to '<strong>\2</strong>'                                                                      

'/(\*)(.*?)\1/' to '<em>\2</em>',      

这很好用! em,粗体和组合都可以正常工作...

但如果用户犯了错误或输入了很多星,一切都会中断。

****hello**** = <strong><em><em>hello</em></strong></em>
*****hello***** = <strong><em><strong>hello</em></strong></strong>
******hello****** = <strong><em></em></strong>hello<strong><em></em></strong>
etc

理想情况下它会创建

****hello**** = *<strong><em>hello</em></strong>*
*****hello***** = **<strong><em>hello</em></strong>**
******hello****** = ***<strong><em>hello</em></strong>***
etc

忽略不需要的星号(这样用户就会清楚他们犯了错误,更重要的是,呈现的 HTML 仍然有效)。

我认为必须有某种方法来修改我的正则表达式来做到这一点,但我无法在我的工作中完成它,即使经过一整天的尝试!

我也会对

的结果感到满意
******hello****** = <strong><em>hello</em></strong>

请问,有人可以帮帮我吗?

还请考虑不均匀的星星。在这种情况下,下面的场景将是理想的。

***hello* = **<em>hello</em>

星星应该是身体的一部分并且未被检测到的时间,例如用户输入:

'terms and conditions may apply*'

or

'I give the film 5* out of 10'

非常感谢

【问题讨论】:

    标签: php regex duplicates preg-replace markdown


    【解决方案1】:

    尝试不同的捕获模式(匹配除* 之外的任何内容一次或多次),

    '/(\*\*\*)([^*]+)\1/'
    

    【讨论】:

    • 谢谢!那当然改善了事情。新结果现在是 **** =

      hello ***** = hello ****** = 你好至少(虽然奇怪)有效的 HTML。您是否知道如何设置,以便奖励星只呈现为 * 并且根本不被修改?另外,如果您能解释为什么您的修改会导致这样的变化,我将非常非常感激。我了解我的原始代码,但不太了解您的修改是如何工作的。

    • 实际上我不能像你现在建议的那样使用这个代码,就像你现在建议的那样:“条款和条件可能适用*”(即*作为正文的一部分)变成一个 EM,而使用之前的模式, 如果它是唯一的星星,它将保持为文本
    • @user2514246 [^* ]+ 可以避免*之间的空格
    • 稍微改进了一些,但使用 4SATRSthis4SATRS 我仍然会以疯狂的线条结束这个当我真的很喜欢明星明星
    • 我现在正在研究一种全新的方法和解决方案。如果我工作得好,我会发布给大家。
    猜你喜欢
    • 1970-01-01
    • 2011-08-24
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 2012-04-16
    • 2014-04-29
    相关资源
    最近更新 更多