So due to a design decision that pervades our application, I need to be able to insert carriage returns into the database. I store the information in a string, and then use Zend's insert, but that escapes the escape character, so the string:
This is an entry\rsplit across two lines
Is actually inserted into the database exactly as written, with the literal \r in the string. I need it to be inserted without escaping the \ so the actual carriage return is put in the database.
The Zend Form has a text box and a multiselect box. The user can enter text into the text box, press a button, and then it gets added to the multiselect box. My code:
$info['choices'] = '';
foreach ($info['choice_list'] as $choice) {
$info['choices'] .= $choice . '\r';
}
$info['choices'] = substr_replace($info['choices'], "", -2);
$info is just an array of table fields => values that I pass to Zend's ->update I use the substr_replace at the end to just trim off the last \r
Problem was resolved, the issue was using single quotes instead of double quotes. Changing my code to:
$info['choices'] = "";
foreach ($info['choice_list'] as $choice) {
$info['choices'] .= $choice . "\r";
}
$info['choices'] = substr_replace($info['choices'], "", -2);
Fixed the issue.
Related
How do I remove quotation from csv?
Code
use Goutte\Client;
$client = new Client();
$response = $client->request('GET', 'http://c-manage.herokuapp.com/login');
$login_form = $response->filter('form')->form();
$login_form["account"] = '1';
$login_form["password"] = 'rpa1001';
$client->submit($login_form);
$client->request('GET', 'http://c-manage.herokuapp.com/client/download?searchQuery%5Bstatus%5D=1&searchQuery%5BregisterStartDate%5D=2010-01-01&searchQuery%5BregisterEndDate%5D=2020-01-01');
$csvResponse = $client->getResponse()->getContent();
return $csvResponse;
response is ...
ID,ステータス,分類,名前,名前(カナ),誕生日,郵便番号,住所,メールアドレス,電話番号,FAX,メモ,登録日,更新日\r\n
213,契約中,個人,"鶴田 秀夫","ツルタ ヒデオ",2000/07/24,1508207,神奈川県吉田市北区佐々木町小林7-4-5,hiroshi.nakatsugawa#yamaguchi.net,0310-282-609,0730-327-581,,"2010-01-25 00:00:
00","2010-01-25 00:00:00"\r\n
221,契約中,個人,"桑原 彩羅","クワハラ サイラ",2008/04/03,8103797,青森県杉山市西区石田町浜田3-4-10,vwakamatsu#kiriyama.jp,090-5710-4350,03849-5-5746,,"2010-01-09 00:00:00","2010-0
1-09 00:00:00"\r\n
237,契約中,個人,"堤 悟志","ツツミ サトシ",2001/04/29,6875750,栃木県佐々木市東区中島町浜田6-6-6,xtsuda#suzuki.com,022-557-4260,0573-01-2822,,"2010-02-07 00:00:00","2010-02-07 00:0
0:00"\r\n
273,契約中,個人,"富永 圭三","トミナガ ケイゾウ",2003/03/16,6314524,静岡県若松市東区廣川町青山10-9-6,yamaguchi.takuma#kondo.com,0020-062-493,06-3862-0779,,"2010-02-13 00:00:00","2
010-02-13 00:00:00"\r\n
.
.
.
What I want to do
I want to remove quotation from csv.
not
213,契約中,個人,"鶴田 秀夫","ツルタ ヒデオ",2000/07/24,1508207,
but
213,契約中,個人,鶴田 秀夫,ツルタ ヒデオ,2000/07/24,1508207,
※This personal information is fake.
What I did
str_replace(""", "", $csvResponse);
str_replace("\xEF\xBB\xBF", '', $csvResponse);
but, not working
The quotes serve a purpose here so you shouldn't be removing them haphazardly. The quotes prevent columns from breaking when they need to contain text that can also contain the delimiter. Like "Foo, bar, baz" for example. Removing the quotes turns this one column into 3 columns, which is obviously wrong.
Though, if you did want to remove them str_replace would certainly not be the way to go, because the quotes can be escaped to be literals inside the column. For example, using str_replace on this column: "He said \"this is crazy\", and left." would strip literals from the column value.
Instead you should load the CSV data with fgetcsv() or str_getcsv() and rebuild the CSV without the quotes like so...
foreach (str_getcsv($csvData) as $row) {
echo implode(",", $row), "\n";
}
This will give you back the literal values of each row without the quotes. Though any literal quotes inside those values will become quotes.
How do I separate my array strings delimiter (|) using the implode function of PHP something like the below String
|Java||PHP||Bootstrap||HTML||CSS|
Actually, I am using a double delimiter to differentiate tags like SQL and MySQL because LIKE "%sql%" will return MySQL results as well. Should be LIKE "%|sql|%"
What I have tried:
$array_service_offer = array();
if (isset($_POST['service_offer'])) {
foreach ($_POST['service_offer'] as $selectedOption) {
array_push($array_service_offer, $selectedOption);
}
//$service_offer = implode(',',$array_service_offer);
$service_offer = '|' . implode('||', $array_service_offer) . '|';
} else {
$service_offer = "";
}
First of all, according to #Qirel comment, I would also recommend to use $array_service_offer[] = $selectedOption; instead of array_push($array_service_offer, $selectedOption);
now for separation, there are several solutions.
One solution is that:
1- to remove first and last | character (it is like trimming)
2- to explode the trimmed string using || delimiter
for that you may use the following code:
$service_offer_trimmed = preg_replace("~(^\|)|(\|$)~", "", $service_offer);
$service_offer_array = explode('||', $service_offer_trimmed);
The other solution is to use straight forward preg_replace function to separate the string. the command follows:
$service_offer_array = preg_split("~(^\|)|(\|\|)|(\|$)~", $service_offer, 0, PREG_SPLIT_NO_EMPTY);
And one more professional solution is that to store your data in database in JSON format rather than delimited code and then when you need to search in your database you may use MySql JSON_CONTAINS function rather than LIKE command.
I have not personally made a performance check on both two solutions but if it not a big database, then it is not a big concern as well.
Therefore, you initial code to get the data and store it into the database will be:
$array_service_offer = array();
if (isset($_POST['service_offer'])) {
foreach ($_POST['service_offer'] as $selectedOption) {
$array_service_offer[] = $selectedOption;
}
}
// $json_service_offer will be saved to the database
$json_service_offer = json_encode($array_service_offer);
the manual on how to use JSON_CONTAINS is in the following link:
12.17.3 Functions That Search JSON Values
I have a form and a user enters eg (note apostrophe at end of string)
My Bday'
Now, I want to strip apostrophes, simple as that... not escape them, not add slashes just get rid of them
Firstly I have the following:
$event_title = mysql_real_escape_string($_POST['event_title']);
echo "<br /><br /><br />event title is $event_title";
Which results in the following being returned:
event title is My Bday\\\'
Why 3 slashes?
So, then I go ahead and deal with this by using the following:
$event_title = str_replace("'", "", $event_title);
$event_title = stripslashes($event_title);
Then I return it again to check results
echo "<br /><br /><br />event title is $event_title";
I get the following:
event title is My Bday\
Any ideas what's happening? I simply want to strip apostophes and slashes but somehow it's not happening
magic_quotes_gpc is off by the way
If I don't use stripslashes therefore leaving them in for MySQL to deal with I get the following error:
You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'Private',
event_notes = '' where user_event_id = '35'' at line 3
update user_events set event_date = '2012-11-17', event_title = 'My Bday\\\',
event_vis = 'Private', event_notes = '' where user_event_id = '35'
OK, a further EDIT:
I tried this:
$event_title = $_POST['event_title'];
$event_title = str_replace("'", "", $event_title);
$event_title = trim($event_title);
$event_title = mysql_real_escape_string($event_title);
echo "<br /><br /><br />event title is $event_title";
and I get this:
event title is My Bday\\
I simply want to get rid of apostrophes, clearly something else is going on here but its got me!
What's happening is this:
mysql_real_escape_string escapes all the characters that should be escaped by adding a slash in front of a character being escaped. But adding just a slash will lead to storing the character as unescaped within the DB, therefore also the slash must be escaped prior to inserting...
That's why You have My BDay\\\'. If this value is stored into a DB the final result will be My BDay\'.
But when You do str_replace("'", "", 'My BDay\\\''); You will end up with My BDay\\\ and after calling stripslashes on this You will get My BDay\ - that is absolutely correct!
So don't bother with how the string looks like after calling mysql_real_escape_string, just store that value into the DB and after retrieving it You will end up with My BDay' again...
EDIT How You come to just one slash from the three after calling stripslasshes? The function goes from the start of the string to its end and looks for any slash escaped characters to remove the escaping slash. So it finds first two slashes and removes one, but still two remains (the one just processed and the third one), so it processes next two slasshes it finds that will result in just one slash remaining...
If You'd call stripslashes on the string My BDay\\\' - that will lead to My BDay'...
EDIT2 My bad... The next two slashes are added probably because You have magic_quotes_gpc ON - turn that off or call mysql_real_escape_string(stripslashes($string)).
One slash to escape the apostrophe, the other to escape the slash that escape the apostrophe.
Internally the mysql interpret the \' how '
in your php settings the string_splash setting is ON and that is why when the string is passed from form - it is already excapped... Now you using mysql_real_escape_string - which excapes "excape character" as well as single quote as well. and that is why three slashes..
Try using this function - which I use a lot
function sanitize( $value )
{
if( get_magic_quotes_gpc() )
{
$value = stripslashes( $value );
}
//check if this function exists
if( function_exists( "mysql_real_escape_string" ) )
{
$value = mysql_real_escape_string( $value );
}
//for PHP version < 4.3.0 use addslashes
else
{
$value = addslashes( $value );
}
return $value;
}
It is not specifically for php 4 or older years... The function works to escape string and make sure it does not double escape it ( which is the question beign asked )
if( function_exists( "mysql_real_escape_string" ) ) - this line escapes if the database connection is available and
else part of that if condition makes sure it works if database connection is not available and php 4 support is added benifit only...
I have a script to export data from MYSQL to a CSV file. the data is numbers, text and special chars. All fields are deliminated with double quotes and separated by commas.
I need to export data in the following form:
"this is a (x2") badly grammorize'd sentence. Yes, "no", maybe & more.","0043","false" etc..
However I can only get it to work when I apply htmlsepcialchars to each field. The data needs to remain as above, but when it comes into Excel or Calc some of the commas and single quotes etc screw it up. Meaning some of the sentence is in one cell and more in another.
$dataResult = mysql_query("SELECT * FROM data");
while ($rowData = mysql_fetch_row($dataResult))
{
for ($j=0;$j<32;$j++)
{
$csv_output .= '"'.htmlspecialchars($rowData[$j]).'",';
}
$csv_output .= "\n";
}
htmlspecialchars is only meant for escaping data inserted into HTML (as the function name suggest). For CSV data, consider writing a function adhering to the CSV standard, especially by using two quotes instead of one.
For example:
function csvspecialchars($msg) {
return str_replace('"', '""', $msg);
}
There may be other characters to escape as well. Check out the standard at RFC 4180.
According to wikipedia, you can escape a double quote by doubling it (eg, "this is a (x2"") badly grammorize'd sentence. Yes, ""no"", maybe & more.","0043","false"). That should also fix the problem with the commas and I can't say why single quotes would be a problem...
The built-in fputcsv function takes care of everything neccesary to output valid csv. Unfortunately it can only output to a file, but there's a workaround in the comments, credit goes to Guile:
<?php
function outputCSV($data) {
$outstream = fopen("php://output", 'w');
function __outputCSV(&$vals, $key, $filehandler) {
fputcsv($filehandler, $vals, ';', '"');
}
array_walk($data, '__outputCSV', $outstream);
fclose($outstream);
}
$mydata = array(
array('data11', 'data12', 'data13'),
array('data21', 'data22', 'data23'),
array('data31', 'data32', 'data23'));
outputCSV($mydata);
/* Output sent :
data11;data12;data13
data21;data22;data23
data31;data32;data23
*/
I have a text ($text) and an array of words ($tags). These words in the text should be replaced with links to other pages so they don't break the existing links in the text. In CakePHP there is a method in TextHelper for doing this but it is corrupted and it breaks the existing HTML links in the text. The method suppose to work like this:
$text=Text->highlight($text,$tags,'\1',1);
Below there is existing code in CakePHP TextHelper:
function highlight($text, $phrase, $highlighter = '<span class="highlight">\1</span>', $considerHtml = false) {
if (empty($phrase)) {
return $text;
}
if (is_array($phrase)) {
$replace = array();
$with = array();
foreach ($phrase as $key => $value) {
$key = $value;
$value = $highlighter;
$key = '(' . $key . ')';
if ($considerHtml) {
$key = '(?![^<]+>)' . $key . '(?![^<]+>)';
}
$replace[] = '|' . $key . '|ix';
$with[] = empty($value) ? $highlighter : $value;
}
return preg_replace($replace, $with, $text);
} else {
$phrase = '(' . $phrase . ')';
if ($considerHtml) {
$phrase = '(?![^<]+>)' . $phrase . '(?![^<]+>)';
}
return preg_replace('|'.$phrase.'|i', $highlighter, $text);
}
}
You can see (and run) this algorithm here:
http://www.exorithm.com/algorithm/view/highlight
It can be made a little better and simpler with a few changes, but it still isn't perfect. Though less efficient, I'd recommend one of Ben Doom's solutions.
Replacing text in HTML is fundamentally different than replacing plain text. To determine whether text is part of an HTML tag requires you to find all the tags in order not to consider them. Regex is not really the tool for this.
I would attempt one of the following solutions:
Find the positions of all the words. Working from last to first, determine if each is part of a tag. If not, add the anchor.
Split the string into blocks. Each block is either a tag or plain text. Run your replacement(s) on the plain text blocks, and re-assemble.
I think the first one is probably a bit more efficient, but more prone to programmer error, so I'll leave it up to you.
If you want to know why I'm not approaching this problem directly, look at all the questions on the site about regex and HTML, and how regex is not a parser.
This code works just fine. What you may need to do is check the CSS for the <span class="highlight"> and make sure it is set to some color that will allow you to distinguish that it is high lighted.
.highlight { background-color: #FFE900; }
Amorphous - I noticed Gert edited your post. Are the two code fragments exactly as you posted them?
So even though the original code was designed for highlighting, I understand you're trying to repurpose it for generating links - it should, and does work fine for that (tested as posted).
HOWEVER escaping in the first code fragment could be an issue.
$text=Text->highlight($text,$tags,'\1',1);
Works fine... but if you use speach marks rather than quote marks the backslashes disappear as escape marks - you need to escape them. If you don't you get %01 links.
The correct way with speach marks is:
$text=Text->highlight($text,$tags,"\\1",1);
(Notice the use of \1 instead of \1)