php - 正则表达式的问题

标签 php regex tags preg-replace bbcode

不久前,我构建了以下正则表达式:

~(?:<a.*?</a>|\[url.*?\[/url]|\[/?[^]]++]|</?[^>]++>)(*SKIP)(*FAIL)|\bcdkey\s*-\s*.*\b~is

这与不在 bbcode 或 html 标记内的每种 cdkey-xxx 相匹配。到目前为止效果很好。

但是,当包含 bbcodes 和 html 标签时,我无法使其正常工作。我想,去掉前面的部分就足够了,但我似乎错了:

~\bcdkey\s*-\s*.*\b~is

使用这个正则表达式,

<a href="https://www.google.de/#q=cdkey-0192xdasas" class="externalURL">https://www.google.de/#q=cdkey-0192xdasas</a>

变成了

<a href="https://www.google.de/#q=***>

[url]https://www.google.de/#q=cdkey-0192xdasas[/url]

变成了

[url]https://www.google.de/#q=***]

虽然预期结果是

<a href="https://www.google.de/#q=***" class="externalURL">https://www.google.de/#q=***</a>

[url]https://www.google.de/#q=***[/url]

我不知道如何解决这个问题。


所以,我试图实现的是替换

[url]https://www.google.de/#q=cdkey-0192xdasas[/url]
[url=https://www.google.de/#q=cdkey-0192xdasas]Test[/url]
[img]https://www.google.de/#q=cdkey-0192xdasas[/img]
[url="https://www.google.de/#q=cdkey-0192xdasas"]Test 3[/url]
https://www.google.de/#q=cdkey-0192xdasas
    Another plaintext cdkey   -   bla
<a href="https://www.google.de/#q=cdkey-0192xdasas" class="externalURL">https://www.google.de/#q=cdkey-0192xdasas</a>
<a href='https://www.google.de/#q=cdkey-0192xdasas'>Le Google</a>

[url]https://www.google.de/#q=***[/url]
[url=https://www.google.de/#q=***]Test[/url]
[img]https://www.google.de/#q=***[/img]
[url="https://www.google.de/#q=***"]Test 3[/url]
Plaintext https://www.google.de/#q=***
    Another plaintext ***
<a href="https://www.google.de/#q=***" class="externalURL">https://www.google.de/#q=***</a>
<a href='https://www.google.de/#q=***'>Le Google</a>

最佳答案

我发现您的正则表达式的问题是 .* 部分。

您在匹配中匹配尽可能多的金额,无需使用s修饰符。

如果您知道您的cdkey始终是数字和字母,您可以这样做。

$text = preg_replace('/cdkey\s*-\s*[a-z0-9]+/i', '***', $text);

参见working demo

关于php - 正则表达式的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19601301/

相关文章:

php - 第 17 行警告 : failed to open stream: Invalid argument in C:\xampp\htdocs\WWW\index. php

php - 根据总迭代次数更改我的 css 类中的宽度

regex - 从专有名称解析通用名称的正则表达式

c# - 用于根据模式将字符串拆分为两个集合的正则表达式

mysql - 如何从文章表 10 个最受欢迎的标签中获取行?

regex - 使用 grep 获取 xml 标签内的文本

php mysql 爆炸数据库插入

php - 如何在没有 "bind_param"的情况下进行更新

javascript - 在 cucumber-js 中检索在特定字符串之前结束的参数

javascript - 使用javascript获取标签的值