首页 > 解决方案 > 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);


?>

标签: phppreg-replace

解决方案


'preg_replace' 需要 3 个参数(参见文档)。

所以在你的情况下应该是:$newName = preg_replace('/[^a-zA-Z0-9]+/', '', $name);

此外,我移动了“^”,因为:

  • 在它的旧位置,它的意思是“在文本的开头匹配这个正则表达式”。

  • 在它的新位置,它的意思是“除了 [a-zA-Z0-9] 之外的任何东西”

因此,现在该函数将所有非字母字符替换为 null(您可以阅读 Johan Sjöberg 对Regex not operator的回答以了解更多信息)。


推荐阅读