php - preg_replace 不剥离输入
问题描述
我试图让它在按下提交按钮的地方,所有输入只留下字母和数字,然后回显到页面上。我没有收到任何错误,但它仍然不会打印出格式化的文本。我可以回显一个 3 行命令,但是在将其转换为输入时我迷路了。
任何人都可以帮我获取代码以按照我想要的方式行事吗?我不是要清理数据或插入数据库。我只是想将由于手指肥大、醉酒或其他原因而无法阅读的单词删除到页面上
我试过了
preg_replace('/^[a-zA-Z0-9]+/', $name)
preg_replace('/^[a-zA-Z0-9]+/', $_POST["name"])
<html>
<head>
<title>test</title>
</head>
<body>
<form id="form" class="appnitro" method="post" action="">
<h2>stripping extra crap</h2>
<div>
<br>
name<br>
<input id="element_1" name="name" type="text" maxlength="20" value="test$%+=-?"/> <br>
test1<br>
<input id="element_1" name="test1" type="text" maxlength="20" value="test$%+=-?"/> <br>
test2<br>
<input id="element_1" name="test2" type="text" maxlength="20" value="test$%+=-?"/> <br>
test3<br>
<input id="element_1" name="test3" type="text" maxlength="20" value="test$%+=-?"/> <br>
</div>
<input id="" class="button_text" type="submit" name="" value="Submit" />
</form>
</div>
</body>
</html>
<?php
if (empty($name) && empty($test1) && empty($test2) && empty($test3)) {
echo 'Please fill in the fields';
return false;
}
if (isset($_POST['submit'])){
implode("", $_POST);
preg_replace('/^[a-zA-Z0-9]+/', $_POST);//testing string to replace $name to letters and numbers only
}
echo 'name with only letters and numbers?<br>';
echo $name;
echo '<br>';
echo '<br>';
echo 'is post array still an array or string after implode?<br>';
echo $_POST;
echo '<br>';
echo '<br>';
echo 'test1 with only letters and numbers?<br>';
echo $test1;
echo '<br>';
?>
--------------------------------
<?php
foreach($_POST as $key=>$value)
{
echo "<br>$key=$value<br>";
}
// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
?>
解决方案
'preg_replace' 需要 3 个参数(参见文档)。
所以在你的情况下应该是:$newName = preg_replace('/[^a-zA-Z0-9]+/', '', $name);
此外,我移动了“^”,因为:
在它的旧位置,它的意思是“在文本的开头匹配这个正则表达式”。
在它的新位置,它的意思是“除了 [a-zA-Z0-9] 之外的任何东西”
因此,现在该函数将所有非字母字符替换为 null(您可以阅读 Johan Sjöberg 对Regex not operator的回答以了解更多信息)。
推荐阅读
- node.js - 在 Firebase 中创建用户后发送电子邮件确认并将数据添加到集合
- servicestack - 从 http 上下文获取 servicestack 角色
- laravel - laravel 强化记住我的功能
- reactjs - 本地主机未加载 - 标题选项卡中的连续旋转
- ios - IOS设备上Flutter firebase上传照片问题
- python - Pandas 在索引上执行数学运算
- javascript - Mongoose 不返回空对象的属性
- c++ - 为什么用 0 清理 1 后,它在位掩码中返回 1
- javascript - 自定义结帐 paytm 集成 - 提供的校验和无效错误 2005
- ansible - 如何在ansible角色之间暂停