如果字符串中的字符数超过160,则显示警告

时间:2015-01-08 16:04:07

标签: php

我想实现像twitter这样的更新后系统,用户可以在160个字符中更新自己的状态。我想添加一些限制,例如,如果用户输入的字符数超过160,那么 update_post.php 文件必须在HTML del tag中向他/她显示警告和额外字符(+160)。 **贝娄是我迄今为止尝试过的代码。但它什么也没输出!**任何帮助都很有用!感谢

sample_update.php

<form action="<?php echo $_SERVER['PHP_SELF'];?>"method="post">
   <textarea name="msg"></textarea>
   <input type="submit"value="Post">
</form>

<?php
  if(strlen($txt)>160) {
      echo "Your post couldn't be submitted as it contains more then 160 chrecters!";
      $txt=$_POST['msg'];
      $checking=substr($txt,160);
      echo "<del style='color:red;'>$checking</del>";
  }
?>

4 个答案:

答案 0 :(得分:4)

$txt设置在if语句中,您需要将其移到

之外
$txt=$_POST['msg'];

if(strlen($txt)>160)
{
     echo "Your post couldn't be submitted as it contains more then 160 chrecters!";
     $checking=substr($txt,160);
     echo "<del style='color:red;'>$checking</del>";
}

答案 1 :(得分:2)

您应该收到有关未定义变量的通知。从我/我们可以看到的$txt开始,$txt在if循环中定义。我已经将您的代码修改为最小的行,但同样有效。

if (isset($_POST['msg'])){
    if (strlen($_POST['msg']) > 160){
        echo "Your post could not be submitted as it contains more than 160 characters!";
        echo "<del style='color:red;'>".substr($_POST['msg'],160)."</del>";
    }

}

我还在isset语句周围包装你的$ _POST,它会在做任何事情之前检查它是否已设置。如果没有设置,那么代码将不会执行并触发一些烦人的错误消息

答案 2 :(得分:1)

这应该适合你:

$_SERVER['SELF']不存在$_SERVER['PHP_SELF']此外,您必须先分配变量,然后才能检查长度。

<form action="<?= $_SERVER['PHP_SELF'];?>"method="post">
    <textarea name="msg"></textarea>
    <input type="submit"value="Post">
</form>

<?php

    if(!empty($_POST['msg'])) {
        $txt = $_POST['msg'];

        if(strlen($txt) > 160) {
            echo "Your post couldn't be submitted as it contains more then 160 chrecters!";

            $checking = substr($txt,160);
            echo "<del style='color:red;'>$checking</del>";
        }
    } 



?>

答案 3 :(得分:0)

首先,您必须使用$_SERVER['PHP_SELF']代替$_SERVER['SELF']

您可能希望移动某些条件,以便可以使用其他内容进行检查。此外,将用户键入的文本插入textarea是一个很好的做法,因此用户dosnt必须重新键入文本。

<?php
    $maxlen = 160;
    $txt=(isset($_POST['msg'])) ? $_POST['msg'] : "";
    $check = strlen($txt) > $maxlen;
?>

<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<textarea name="msg"><?php echo $txt; ?></textarea>
<input type="submit" value="post">
</form>
<?php
if ($check){
    echo "Your post couldn't be submitted as it contains more then $maxlen chrecters!";
    $checking = substr($txt,$maxlen);
    echo "<del style='color:red;'>$checking</del>";
} else {
    echo "You are good to go ma man - do something";
}
?>