【问题标题】:Regex replace surrounding characters while maintaining the string between正则表达式替换周围的字符,同时保持字符串之间
【发布时间】:2016-07-20 01:33:03
【问题描述】:

我正在使用 PHP 尝试将文本从一种 Markdown 风格转换为另一种风格。

例如,如果我有字符串 **some text**,则应将其替换为字符串 '''some text'''(每边的 ** 将替换为 ''' 三重撇号)。但是,字符串**some other text 不应进行任何替换,因为它不以** 结尾

目前,我正在使用以下代码:

function convertBoldText($line){
    #Regex replace double asterisk IF if is FOLLOWED by a non-asterisk character
    $tmp = preg_replace('/\*{2}(?=[^\*])/', "'''", $line);
    #Regex replace double asterisk IF if is PRECEDED by a non-asterisk character
    return preg_replace('/(?<=[^\*])\*{2}/', "'''", $tmp);
  }

但是,此代码还替换了以双星号开头但不以双星号结尾的字符串中的星号,这是不应该的。

当且仅当双星号匹配时,我如何使用正则表达式替换双星号(例如,打开和关闭双星号存在并相互匹配)?

最大的挑战来自您将前面提到的两个示例结合在一起的情况,例如:

** these first asterisks should NOT be replaced **but these ones SHOULD**

【问题讨论】:

  • 为什么不替换这个 - ** these first asterisks should NOT be replaced **

标签: php regex string preg-replace preg-match


【解决方案1】:

您可以使用正则表达式来匹配**,其后跟除** 之外的任何文本,然后跟**

 function convertBoldText($line){
return preg_replace('/\*{2}(?!\s)((?:(?!\*{2}).)*)(?<!\s)\*{2}/s', "'''$1'''", $line);

}

IDEONE demo

正则表达式解释

  • \*{2} - 2 *s
  • (?!\s) - 两个星号后面不能有空格
  • ((?:(?!\*{2}).)*) - 第 1 组捕获除 ** 之外的任何文本
  • (?&lt;!\s) - 之前不能有空格...
  • \*{2} - 两个*s
  • /s - 点也匹配任何字符和换行符。

一个更好的选择可以是

return preg_replace('/\*{2}(?!\s)([^*]*(?:\*(?!\*)[^*]*)*)(?<!\s)\*{2}/', "'''$1'''", $line);

【讨论】:

  • 这对我有用,老实说,答案比我预期的要简单得多。谢谢!完美运行。
猜你喜欢
  • 2014-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-26
  • 1970-01-01
  • 1970-01-01
  • 2013-01-21
  • 2018-07-13
相关资源
最近更新 更多