匹配两个部分相同次数

发布于 2024-10-09 21:23:33 字数 239 浏览 0 评论 0原文

我正在搜索代码来解析以下内容:

some texttext

我需要删除不必要的 出现,以便输出为:

some texttext

我编写了一个正则表达式,它执行了一次:

/[ ^<]*/i

如何在 上使此工作次数相同?

I'm searching for code to parse the following:

some texttext

I need to remove unnecessary <span> occurrences, so that output is:

some texttext

I wrote a regex, which does this once:

/[^<]*</SPAN>/i

How do I make this work same number of times on both <span> and </span>?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

娇柔作态 2024-10-16 21:23:33
$result = preg_replace(
    '%(?<=<span>)        # Assert that there is a directly preceding span tag
    <span>               # Match a span tag
    ((?:(?!</?span>).)*) # Match the contents of the tag only if they do not include another span tag
    </span>              # Match a closing span tag
    (?=</span>)          # Assert that there is a directly following span tag
    %six', 
    '\1', $subject);

将适用于您的示例,但必须应用两次,因为它每次迭代都会删除一层嵌套 span 标记。

因此,对于任意嵌套的标签,您需要为每个嵌套级别调用一次。

$result = preg_replace(
    '%(?<=<span>)        # Assert that there is a directly preceding span tag
    <span>               # Match a span tag
    ((?:(?!</?span>).)*) # Match the contents of the tag only if they do not include another span tag
    </span>              # Match a closing span tag
    (?=</span>)          # Assert that there is a directly following span tag
    %six', 
    '\1', $subject);

will work on your example, but it has to be applied twice because it removes one "layer" of nested span tags per iteration.

So, with arbitrarily nested tags, you'd need to call this once for each level of nesting.

错々过的事 2024-10-16 21:23:33

您可以尝试查看 后面是否直接跟着另一个 及其匹配的 直接前面加上另一个

但实际上您不能说该跨度毫无用处,因为可以将标记添加到这些特定跨度中。如果没有任何标记,那么最后剩余的跨度也毫无用处,也可能被删除。

You could try to see if a <span> is directly followed by another <span> and its matching </span> is directly prepended by another </span>.

But you cannot actually say that that span will be useless, because markup can be added to those specific spans. If there isn't any markup, the last remaining spans are useless as well and might just as well be removed too.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文