Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove the NULL character from string

Tags:

php

I have a PHP variable that contains a string which represents an XML structure. This string contains ilegal characters that dont let me build a new SimpleXMLElement object from the string. I dont have a way to ask the source of the content to modify their response, so I need to execute some cleaning on this string before I create a SimpleXMLElement object.

I believe the character causing the problem is a (0x00 (00) HEX) character, and its located within one of the Text Nodes of this string XML.

What is the best way to remove this character or other characters that could break the SimpleXMLElement object.

like image 268
Benjamin Ortuzar Avatar asked Mar 13 '09 12:03

Benjamin Ortuzar


People also ask

How do I remove a null character?

Using the -d switch we delete a character. A backslash followed by three 0's represents the null character. This just deletes these characters and writes the result to a new file.

How do you remove a null character in Python?

line = line. rstrip() will do the job. Unlike strip(), rstrip() only removes trailing whitespace characters. I tried it with null spaces on REPL and it worked.

How do you remove null characters from a string in Java?

A short answer: you could use the String. replace() method to replace the 0 character with another character, or the replaceAll() method to replace it with an empty String.

How do you get rid of null in Java?

string. replace("null", ""); You can also replace all the instances of 'null' with empty String using replaceAll.


2 Answers

$text = str_replace("\0", "", $text); 

will replace all null characters in the $text string. You can also supply arrays for the first two arguments, if you want to do multiple replacements.

like image 123
Joey Avatar answered Sep 22 '22 18:09

Joey


trim() will also remove null characters, from either end of the source string (but not within).

$text = trim($text);

I've found this useful for socket server communication, especially when passing JSON around, as a null character causes json_decode() to return null.

like image 25
bigtallbill Avatar answered Sep 22 '22 18:09

bigtallbill