janeloulou janeloulou - 12 days ago 9
PHP Question

Php- Eliminate characters while reading file

I would I am using PHP. I am reading from a file but I would like to eliminate the following characters from the file wherever they are: '' and { }.

I tried to use the trim function but the characters "',{ and }" are still present in the output:

$txt_file = file_get_contents('out.txt');
$rows = explode(",", $txt_file);
array_shift($rows);

foreach($rows as $row => $data)
{
//get row data
$row_data = explode(':', $data);
trim($row,"'");
trim($row,"{");
trim($row,"}");
$info[$row]['state'] = $row_data[0];
$info[$row]['action'] = $row_data[1];
echo $info[$row]['state'] . '<br />';
echo $info[$row]['action'] . '<br />';
echo '<br />';
}


Do you have any idea how to do it?
Thanks

Answer

I assume you want to remove ' { and } from $row

If it is, then replace

trim($row,"'");
trim($row,"{");
trim($row,"}");

with

$row = str_replace(['\'', '{', '}'], '', $row);

Note: trim — Strip whitespace (or other characters) from the beginning and end of a string. Moreover you didn't store trimmed data to any variable so literally you will not get trimmed data. You want to replace characters wherever it is found so use str_replace or preg_replace. Please check PHP manual for more details