RegEx正则表达式获取ID

时间:2012-06-25 06:14:33

标签: php regex

给出以下字符串:

  • [download id =“1”]
  • [download id =“1”attr =“”]
  • [download attr =“”id =“1”]
  • [download attr =“”id =“1”attr =“”]

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

6 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

试试这个:

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

函数调用:

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

答案 2 :(得分:0)

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

有人建议,如果你想匹配更多字段,我建议你删除正则表达式并找到能够解析你传递的字符串的东西。

答案 3 :(得分:0)

这也是一个解决方案

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

您在捕获第1组时找到了结果

here on Regexr

\[download匹配" [下载"

[^\]]*是一个否定的角色类,匹配所有不是"]" (或多次)

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

(\d*)是一个匹配0位或更多位数的抓取组,您可以将*更改为+以匹配一个或多个。

<子> What absolutely every Programmer should know about regular expressions

答案 4 :(得分:0)

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

test.ini

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

和index.php

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

答案 5 :(得分:0)

这是我的解决方案:

<?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与 ^ 结尾并结束 $ 分隔符,而是使用 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属性:)

相关问题