【发布时间】: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