【问题标题】:Regular Expression: Replace multiple input fields with their values正则表达式:用它们的值替换多个输入字段
【发布时间】:2015-07-08 18:00:20
【问题描述】:

我想使用正则表达式将输入标签替换为其对应的值。 搜索必须包含输入的名称,因为我有多个相同形式的输入需要替换。

例如,我需要以下字符串:

<input value="Your Name" name="custom_field_1">

变成:

Your Name

我当前的代码如下所示:

foreach ($_POST as $key => $value) {
   if($key == 'post_id') continue;
   $content = preg_replace("/<\s* input [^>]+ >/xi", htmlspecialchars($value), $content);
}

但是,这会将所有输入替换为第一个值,因此我需要优化正则表达式以包含名称。

非常感谢您的帮助!

  • 西普里安

【问题讨论】:

  • 为什么 $_POST 包含 html &lt;input value="Your Name" name="custom_field__29541"&gt; ?也许,你显示var_dum($_POST)
  • var_dump for $_POST: array(7) { ["post_id"]=&gt; string(4) "4495" ["custom_field_1"]=&gt; string(7) "Value 1" ["custom_field_2"]=&gt; string(7) "Value 2" ["custom_field_3"]=&gt; string(7) "Value 3" ["custom_field_4"]=&gt; string(7) "Value 4" ["custom_field_5"]=&gt; string(7) "Value 5" ["custom_field_6"]=&gt; string(7) "Value 6" }
  • echo $_POST["post_id"]; // 4495你不需要任何替换
  • echo $_POST["custom_field_1"]; // Value 1
  • 我找到了一个有效的正则表达式:$content = preg_replace("#&lt;input([^&gt;]*)name=['\"]".preg_quote($key)."['\"]([^&gt;]*)&gt;#Uis", htmlspecialchars($value), $content); 谢谢大家的帮助!

标签: php regex forms input html-parsing


【解决方案1】:

您可以匹配整个字符串,使用括号 (..) 捕获值,创建一个捕获组,并将匹配替换为 $1 - 第一个捕获组。

&lt;input value="(.+?)" name=".*?"&gt;

https://regex101.com/r/rH1wA2/3

尝试: preg_replace("&lt;input value=\\"(.+?)\\" name=\\".*?\\"&gt;", $1, $str)

请注意,此正则表达式包含“值”、“名称”甚至空格。如果您的字符串有时看起来不同,您必须考虑到这一点并相应地更改正则表达式。 &lt;input value="(.+?)"[^&gt;]*&gt;,例如,替换你想要的值之后的任何内容。

【讨论】:

    【解决方案2】:

    这应该可行。
    只需将匹配替换为$1

     # (?s)<input(?=\s)(?>(?:(?<=\s)value\s*=\s*"([^"]+)"|".*?"|'.*?'|[^>]*?)+>)(?(1)|(?!))
    
     (?s)
     <input                        # Input tag
     (?= \s )
     (?>                           # Atomic grouping
          (?:
               (?<= \s )
               value  \s* = \s*              # 'value' attribute
               "
               (                             # (1 start), 'value' data
                    [^"]+ 
               )                             # (1 end)
               "
            |  " .*? "
            |  ' .*? '
            |  [^>]*? 
          )+
          >
     )
     (?(1)                         # Conditional - Only input tags with a 'value' attr
       |  (?!)
     )
    

    示例:

    <input type="hidden" value="Special:Search" name="title" />
    

    输出:

     **  Grp 0 -  ( pos 0 , len 59 ) 
    <input type="hidden" value="Special:Search" name="title" />  
     **  Grp 1 -  ( pos 28 , len 14 ) 
    Special:Search  
    

    【讨论】:

      猜你喜欢
      • 2011-10-26
      • 1970-01-01
      • 2011-09-27
      • 1970-01-01
      • 1970-01-01
      • 2015-02-21
      • 2014-06-16
      • 2017-08-22
      • 2021-03-13
      相关资源
      最近更新 更多