Using PHP to do a file_get_contents
on a *.txt file. Then inserting the data into MySQL. Values are inserting null. The null is caused by a non breaking space and a replacement charcter from an excel export. I figured that by copying the characters from the text file into a unicode inspector .
Did the same with the replacement character. Copied the text and pasted it here to confirm.
Tried many str_replace
and preg_replace
but no luck. Tried nearly everything on this SO question and found this worked.
$some_text_with_non_breaking_spaces = "Christ O'Connory";
$clean_text = hex2bin(str_replace('c2a0', '20', bin2hex($some_text_with_non_breaking_spaces)));
echo $clean_text;
BUT it didn't when I put it inline with the file_get_contents()
method.
Any idea how to resolve the null value with preg_replace
, str_replace
or other methods?
Here's all the versions I've tried:
$name = str_replace('\A0\00', ' ', $nbsp);
$name = str_replace('c2a0', '20', $nbsp);
$name = str_replace('\xc2\xa0', ' ', $nbsp);
$name = str_replace('~\xc2\xa0~', ' ', $nbsp);
$name = str_replace('\xC2\xA0', ' ',$nbsp);
$name = str_replace(' ', ' ',$nbsp);
$name = hex2bin(str_replace('c2a0', '20', bin2hex($nbsp))); // this did work but not when putting inline with original code.
$name = preg_replace('#[A-Za-z\,\.\'\-\_]#', ' ', $nbsp);
$name = preg_replace('\x{00a0}', ' ', $nbsp);
$name = preg_replace('~\x00\xa0~', ' ', $nbsp);
$name = preg_replace('~\xc2\xa0~', ' ', $nbsp);
$name = preg_replace('\s\s+', ' ', $nbsp);
$name = preg_replace('/\s+/', ' ', $nbsp);
$name = preg_replace('~\x{c2a0}~siu', ' ', $nbsp);
$name = preg_replace('/\s/u', ' ', $nbsp);
$name = preg_replace('/[^\w\d\p{L}]/u', ' ',$nbsp);
Here is a snippet of data from the file I was attempting to do a file_get_contents on.
SupervisorGivenName SupervisorSurName row_date logid item_name acdcalls AHT AvgHoldTime transferred CntOBCalls calls
Ders Schmid 09/02/2015 5054589 Christ O'Connory 26 420 112 4 0 0
Nic Flemg 09/02/2015 5054596 Mica Wit 28 543 32 6 0 0
Insert statement:
$bb_query = "INSERT INTO `tier1_bb_agent_daily` (`date`,`loginID`,`empID`,`firstname`,`lastname`,`supID`, `supName`,`acd_calls`,`paetec_acd_calls`,`aht`,`avg_hold_time`,`transferred`,`outbound_call_count`)
VALUES ('{$row['date']}','{$row['loginID']}','{$empID}','{$firstname}','{$lastname}','{$supid}','{$newSupName}',{$row['acd_calls']},{$row['paetec_acd_calls']},{$row['aht']},{$row['avg_hold_time']},{$row['transferred']},{$row['outbound_call_count']})
ON DUPLICATE KEY UPDATE firstname = '{$firstname}', lastname = '{$lastname}',empID = '{$empID}', supID = '{$supid}', supName = '{$newSupName}',acd_calls = {$row['acd_calls']}, aht = {$row['aht']}, paetec_acd_calls = {$row['paetec_acd_calls']}, avg_hold_time = {$row['avg_hold_time']}, transferred = {$row['transferred']}, outbound_call_count = {$row['outbound_call_count']}";
$db->query($bb_query);