【问题标题】:PHP use preg_match_all to extract attribute names from stringPHP 使用 preg_match_all 从字符串中提取属性名称
【发布时间】:2019-01-25 08:09:29
【问题描述】:

我正在使用以下代码将字符串拆分为匹配数组:

$text = 'text required name="first_name" label="First Name"';
preg_match_all('/"(?:\\\\.|[^\\\\"])*"|[^\s"]+/', $text, $matches);
print_r($matches);

结果是:

Array
(
    [0] => Array
        (
            [0] => text
            [1] => required
            [2] => name=
            [3] => "first_name"
            [4] => label=
            [5] => "First Name"
        )

)

但我需要的结果是:

Array
(
    [0] => Array
        (
            [0] => text
            [1] => required
            [2] => name="first_name"
            [3] => label="First Name"
        )

)

我试过了,但没用:

preg_match_all('/="(?:\\\\.|[^\\\\"])*"|[^\s"]+/', $text, $matches);

谁能告诉我哪里出错了?谢谢

【问题讨论】:

  • explode(' ',$string);
  • 您是否尝试将正则表达式用于 HTML 字符串?
  • 我看到的主要问题是 | 这意味着搜索引号之间的任何文本或任何不是空格或双引号的文本。您最好使用explode 来简单地拆分文本值,或者如果您出于某种原因确实需要正则表达式,类似于:([^\s"]+(="\w*")*)。我有点累了,所以可能不完全是这样,但或多或​​少应该给你一个跳跃点。
  • @splash58:这也是我的第一个想法,但它不会工作,因为它会将 label="First Name" 拆分为单独的值,因为它有一个空格
  • @Justinas 不,我的问题中的字符串不是 HTML

标签: php regex string preg-match-all


【解决方案1】:

您可以在preg_split() 中使用模式/\s(?![\w\s]+\")/ 将字符串按不在值中的空格分割。

$res = preg_split("/\s(?![\w\s]+\")/", $text);

检查结果在demo

【讨论】:

  • 如果值3v4l.org/T9CWh中有多个空格,这将不起作用
  • @Mohammad 感谢您的帮助,但实际上尼克是正确的,这个问题没有解决,它需要使用任意数量的空格
  • @TheBobster 我无法理解问题,它也适用于多个空间3v4l.org/ag1He
  • @Mohammad 好的,看起来您编辑了答案,现在它可以使用多个空格,所以谢谢!
  • name="first diff-name" 怎么样?
【解决方案2】:

如果你想使用preg_match_all,这里有一个工作代码:

$text = 'text required name="first_name" label="First Name"';
preg_match_all('([a-zA-Z_]*[=]["][a-zA-Z_]*["]|[a-zA-Z_]*[=]["][ a-zA-Z]*["]|[a-zA-Z]+)', $text, $matches);
print_r($matches);

【讨论】:

    猜你喜欢
    • 2014-03-06
    • 2011-11-05
    • 2012-05-27
    • 2013-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多