CloudyKooper
CloudyKooper

Reputation: 717

Why is my php trim() function not working?

I'm trying to use trim to remove the underline character from the data that is returned in the $_POST array. I tried using

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

but the text does not seem to return as one single string. It's broken between each entry. Then I tried trim like this:

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

When I use the trim function nothing happens it does not remove the _ character. My eventual goal is to put a comma delimited list in my database as a single string. Why would my trim() function not work in this case?

Upvotes: 3

Views: 11481

Answers (3)

Muhammad Arslan
Muhammad Arslan

Reputation: 91

try

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
------------------------------------------------------------------------------------- */

Upvotes: 0

CloudyKooper
CloudyKooper

Reputation: 717

I found some
when I viewed the page resource. I don't have them in my code so this is confusing. I finally had to do a combination of str_replace() and rtrim() like this:

 $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";

Upvotes: 0

Alex Shesterov
Alex Shesterov

Reputation: 27525

First, trim() takes arguments in the opposite order: $str, then $character_mask. So you should have used: $post_Value = trim($str, "_");

Second, trim() strings the masked characters only from the beginning and end of the string. It doesn't remove any masked characters from the string if they are surrounded by non-masked characters.


You should actually use str_replace() with an empty replacement string (you've tried a single space as replacement):

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

If you also want to remove <br> tags (in its typical variations), you may do so via single str_replace() call, as follows:

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

See str_replace() docs for details.

Upvotes: 4

Related Questions