【发布时间】: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
<input value="Your Name" name="custom_field__29541">?也许,你显示var_dum($_POST)? -
var_dump for $_POST:
array(7) { ["post_id"]=> string(4) "4495" ["custom_field_1"]=> string(7) "Value 1" ["custom_field_2"]=> string(7) "Value 2" ["custom_field_3"]=> string(7) "Value 3" ["custom_field_4"]=> string(7) "Value 4" ["custom_field_5"]=> string(7) "Value 5" ["custom_field_6"]=> string(7) "Value 6" } -
echo $_POST["post_id"]; // 4495你不需要任何替换 -
echo $_POST["custom_field_1"]; // Value 1 -
我找到了一个有效的正则表达式:
$content = preg_replace("#<input([^>]*)name=['\"]".preg_quote($key)."['\"]([^>]*)>#Uis", htmlspecialchars($value), $content);谢谢大家的帮助!
标签: php regex forms input html-parsing