1

我是 RegEx 的新手,我正在寻找在另一个 ul 的一些子 ul 周围添加 li 的最简单方法。我得到的例子:

我想:

我尝试了几种方法,但我的主要问题是将替换只发生在另一个 ul 的 ul 子项中的正则表达式中(我尝试使用 preg_replace)

你有什么想法或建议吗?

非常感谢您的帮助,

尼古拉斯

4

1 回答 1

0

尝试这个:

$result = preg_replace('%(?s)(?<=</li>)(\s*<ul>.+?</ul>)%im', '<li>$1</li>', $subject);

正则表达式解释:

<!--
(?is)(?<=</li>)(\s*<ul>.+?</ul>)

Options: case insensitive; ^ and $ match at line breaks

Match the remainder of the regex with the options: case insensitive (i); dot matches newline (s) «(?is)»
Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=</li>)»
   Match the characters “&lt;/li>” literally «</li>»
Match the regular expression below and capture its match into backreference number 1 «(\s*<ul>.+?</ul>)»
   Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s*»
      Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
   Match the characters “&lt;ul>” literally «<ul>»
   Match any single character «.+?»
      Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?»
   Match the characters “&lt;/ul>” literally «</ul>»
-->
于 2012-05-08T10:21:38.727 回答