php正则表达式preg_match少于字符破坏代码

时间:2014-05-17 13:35:47

标签: php regex preg-match

我试图整理一个preg_match来发现以下模式

< [alphanumericstring] id [space or nospace] = [space or nospace] [doublequotes or single quotes] a text string [doublequotes or single quotes] [space or nospace]>

因此代码将识别:      和     

这有效:     if (preg_match("/[a-z0-9] id\s*=\s*[\"\']".$variable."\s*[\"\']\s*>/i", $document_content))

但是当我添加第一个&#39;&lt;&#39;像这样:     if (preg_match("/<[a-z0-9] id\s*=\s*[\"\']".$variable."\s*[\"\']\s*>/i", $document_content))

我已经尝试过&lt;同样。最后的&#39;&#39;没有引起任何问题,但有一些特殊的方式&#39;&lt;&#39;应该进入?

2 个答案:

答案 0 :(得分:1)

一些注意事项:

  1. 对于空格,请使用实际的space()字符。 \ s也会匹配制表符和换行符
  2. 使用?对于可选(1或0个实例)。 *表示0或更多实例
  3. 打开/关闭标签。 PCRE使用LT / GT语法支持命名参数。
  4. 试试这个:

    <?php
    if (preg_match("/\\<[a-z0-9]+ id ?= ?[\"']{$variable} ?[\"'] ?\\>/i", $document_content))
    

答案 1 :(得分:1)

/\<[a-z0-9]+\sid\s?\=\s?(?:'|")$YOUR_VARIABLE_STRING(?:'|")\s?\>/g

尝试使用这个。 (用http://regexr.com/制作)

相关问题