用于获取 ID 的正则表达式正则表达式


RegEx Regular Expression to get ID

给定以下字符串:

  • [下载 ID="1"]
  • [下载 id="1" attr="]
  • [下载 attr=" id="1"]
  • [下载 attr=" id="1" attr="]

ID 始终是一个数字。我需要一个正则表达式,它总是给我这个数字,以便通过PHP使用,最好通过 http://www.solmetra.com/scripts/regex/index.php 演示。

preg_match_all('/id="('d+)"/', $data, $matches);

试试这个:

/'[download.*?id='"('d+)'"/

调用的函数:

preg_match_all('/'[download.*?id='"('d+)'"/', '{{your data}}', $arr, PREG_PATTERN_ORDER);

假设您将始终有一个id字段并且它将始终括在引号(")中,您可以尝试类似正则表达式的内容,例如:id="('d+)"。这将捕获数字并将其放在一个组中。您可以查看此处,了解如何访问这些组。

正如有人建议的那样,

如果你想匹配更多的字段,我建议你去掉正则表达式,找到一些能够解析你正在传递的字符串的东西。

您可以轻松使用ini文件,而不是需要的正则表达式,例如:

测试.ini

[download]
id=1
attr = ""
[download2]
id=2
attr = "d2"

和索引.php

$ini = parse_ini_file('test.ini', true);
print_r($ini);
这是我

的解决方案:

<?php
    $content =
<<<TEST
[download id="1"]
[download id="2" attr=""]
[download attr="" id="3"]
[download attr="" id="4" attr=""]
TEST;
    $pattern = '/'[download.*[ ]+id="(?P<id>[0-9]+)".*']/u';
    if (preg_match_all($pattern, $content, $matches))
        var_dump($matches);
?>

适用于单行输入(读入$matches['id'][0])或多行输入(如示例,迭代$matches['id'] 数组)。

注意:

  • 不要将 preg_match 与 start ^ 和 end $ 分隔符一起使用,而是使用 preg_match_all 不带分隔符
  • 不要使用"s"PCRE_DOTALL修饰符
  • 如果您希望正则表达式同时适用于"下载"或"下载",请使用"i"修饰符
  • 如果输入是 UTF-8 编码字符串,请使用"u"修饰符

http://it.php.net/manual/en/function.preg-match-all.php

http://it.php.net/manual/en/reference.pcre.pattern.modifiers.php

上面的例子将输出这个:

array(3) {
  [0]=>
  array(4) {
    [0]=>
    string(17) "[download id="1"]"
    [1]=>
    string(25) "[download id="2" attr=""]"
    [2]=>
    string(25) "[download attr="" id="3"]"
    [3]=>
    string(33) "[download attr="" id="4" attr=""]"
  }
  ["id"]=>
  array(4) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "2"
    [2]=>
    string(1) "3"
    [3]=>
    string(1) "4"
  }
  [1]=>
  array(4) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "2"
    [2]=>
    string(1) "3"
    [3]=>
    string(1) "4"
  }
}

因此,您可以读取在 $matches['id'] 数组上循环的 ID 属性:)

这也是一个解决方案

'[download[^']]*id="('d*)

在捕获组 1 中找到结果

在正则表达式上看到它

'[download匹配"[下载"

[^']]* 是一个否定字符类,匹配所有不是"]"的内容(o 或更多次)

id="字面上匹配"id="

('d*)是匹配 0 位或多位数字的捕获组,则可以将*更改为+以匹配一个或多个数字。

每个程序员都应该知道的关于正则表达式的知识