为什么我的php trim()函数不能用?

问题描述 投票:3回答:3

我试图使用trim函数从$_POST数组中返回的数据中删除下划线字符。 我试着用

 $post_Value= str_replace("_", " ", $key) 

但文本似乎并不是作为一个单独的字符串返回。 每个条目之间都是断开的。然后我试着像这样修剪。

 <?php
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);

 // Test if connection succeeded

 if (mysqli_connect_errno())
    {
    die("Database connection failed: " . mysqli_connect_error() . " (" .  mysqli_connect_errno() . ")");
}

 if (isset($_POST))
    {
    $str = "";
   foreach($_POST as $key => $value)
    {
    $str = $str . $key . ",";
    }

   $post_Value = trim("_", $str);
   }

   $query = "UPDATE player_match SET categoryOption='$$post_Value' WHERE id=1";
 ?>

当我使用trim函数时,什么都没有发生,它没有删除... ... _ 字符。 我的最终目标是把一个以逗号分隔的列表作为一个单一的字符串放在数据库中。 为什么我的 trim() 函数在这种情况下不工作?

更新。 发现 <br/> 在view页面资源中,所以我不得不做以下组合。

       $post_Value= str_replace("<br_/>", "", $str);
        $post_Value2= str_replace("_", " ", $post_Value);
        $post_Value3= rtrim($post_Value2,",submit,");
        echo $post_Value3;


        $query="UPDATE player_match SET categoryOption='$post_Value3' WHERE   id=1";
php trim
3个回答
4
投票

首先是 trim() 需要 顺序相反: $str,那么 $character_mask. 所以你应该用。$post_Value = trim($str, "_");

第二个。trim() 屏蔽字串 自始至终 的字符串。如果字符串被非屏蔽字符包围,它不会从字符串中删除任何屏蔽字符。


实际上,您应该使用 str_replace() 用一个空的替换字符串 你试过用一个空格作为替换)。

$post_Value= str_replace("_", "", $key)

如果你也想删除 <br> 标签(在其典型的变化中),您可以通过单一的 str_replace() 呼叫,如下。

$post_Value= str_replace(array("_", "<br>", "<br/>", "<br />"), "", $key)

str_replace() docs的细节。


0
投票

我查看页面资源的时候发现了一些。我的代码中没有它们,所以这让我很困惑。最后我不得不把str_replace()和rtrim()结合起来,像这样。

 $post_Value= str_replace("<br_/>", "", $str); $post_Value2= str_replace("", " ", $post_Value); $post_Value3= rtrim($post_Value2,",submit,"); echo $post_Value3; //echo $editedStr=str_replace("", " ", $str); $query="UPDATE player_match SET categoryOption='$post_Value3' WHERE id=1";

0
投票

试试

preg_replace( '/^\W*(.*?)\W*$/', '$1', $string )

/* -----------------------------------------------------------------------------------
  ^                        the beginning of the string
    \W*                    non-word characters (all but a-z, A-Z, 0- 9, _) (0 or more times (matching the most amount possible))
    (                      group and capture to \1:
      .*?                  any character except \n (0 or more times(matching the least amount possible))
    )                      end of \1
    \W*                    non-word characters (all but a-z, A-Z, 0-9, _) (0 or more times (matching the most amount possible))
  $                        before an optional \n, and the end of the string
------------------------------------------------------------------------------------- */
© www.soinside.com 2019 - 2024. All rights reserved.