i want to replace any " ' " that people post on my form with nothing as it's causing errors down the line at the moment i've tried this
$visit = str_replace("","'",$this->input->post('visit_type'));
This Changes nothing, is their an easier way around this?
Bare in mind im just a humble apprentice developer. Don't get too technical.
You could use htmlspecialchars and addslashes that convert special characters to HTML entities and quote string with slashes but if you want to use str_replace, the correct usage is $visit = str_replace("'","",$this->input->post('visit_type'));
The first paramater is the search value and the second the replacement value that replaces found search values
str_replace("'","",$this->input->post('visit_type'));
please read the documentation on str_replace..
http://uk1.php.net/str_replace
Swap your parameters around:
$visit = str_replace("'","",$this->input->post('visit_type'));
Related
I get a string from the frontend which has a line break in it. It is saved in an array which looks like this:
[address] => Array (
[0] => Foo
Bar
)
I then use json_encode() on the array before writing it into the SQL DB:
$string = json_encode( $string, JSON_UNESCAPED_UNICODE );
This turns the array into:
{"address":["Foo\r\nBar"]}
Unfortunately the DB doesn't like \r or \n if not escaped, so it gets rid of the \r and \n.
So the first question is, is there a function that I can use to properly escape the string, so it can be written properly into the DB without losing the line break?
I didn't find any function for that, so I tried to use str_replace to just replace the \r\n with \\n. The function is:
$string = str_replace(["\r\n","\r","\n"], "\\n", $string);
This however does not work. I don't know why. The function itself works, as I tried to replace only "n" with "bla" and it worked. However the moment I try to replace the backslash it does not find anything to replace. I don't know if some "special" backslash character is used here or what else could be going on here.
This is driving me nuts, seriously. So I hope somebody can help me out. Thanks in advance.
Problem :
Your str_replace is not working because you are using double quotes.
Solution :
You should replace your double quotes with single quotes and then the magic will happen :D
$string = str_replace(['\r\n','\r','\n'], '\\n', $string);
EXTRA USEFUL INFORMATION : For more you should take a look at for details as it's useful to get to know the difference between double quotes and single quotes as:
What is the difference between single-quoted and double-quoted strings in PHP?
It depends on how you insert the string into the DB. However you do it, you need to escape it properly.
If you're using PDO, you can achieve this like this:
$conn = new PDO(.....);
$sql_str = $conn->quote($string);
$conn->exec("INSERT INTO table (str_value) {$sql_str}");
Or, better use a prepared statement:
$conn = new PDO(.....);
$stm = $conn->prepare("INSERT INTO table (str_value) :value");
$stm->execute(array(':value' => $string));
Hope that works.
Storing JSON directly in a database? Yeuch!
However if you really must do it, then why do you feel the need to change the representation of the data? When you run it back through a JSON decoder you wil get the original data back. The problem is only how to get it into a safe format for insertion into your database.
That you have created this from a PHP array implies you've got NO EXCUSE for not checking the content of the data before you save it (not that writing data supplied directly from Javascript is in any way valid or forgiveable).
is there a function that I can use to properly escape the string
Yes, there are several - but you've not told us which API you are using. This is not some magical trick to solve the problem you currently find yourself in - escaping any data you write to your database properly is essential to prevent SQL injection.
In addition to the PDO methods mentioned by Alex, you can do it in the (deprecated) mysql extension using mysql_escape_string/mysql_real_escape_string or in mysqli procedural code with mysql_escape_string / mysqli_real_escape_string or msqli_prepare + mysqli_bind_param. The mysqli functions also have object oriented representations.
I am trying to display a data into textarea which is fetched from tables that i have submitted via another form. The issue comes up when a new line is entered.
The data getting displayed in the textarea is as
lin1\r\nlin2
it should be like
lin1
lin2
I have tried nl2br but it does not work as expected.
How can i make things optimized. Thanks
This problem can be solved using stripcslashes() when outputting your data.
Please note that the method above is different from stripslashes() which doesn't work in this case.
I tried using nl2br but it wasn't sufficient either.
I hope str_replace saves you.
<?php
$str='lin1\r\nlin2';
$str=str_replace('\r\n','<br>',$str);
echo $str;
OUTPUT:
lin1
lin2
This is a common question and the most common answers are ln2br or str_replace.
However this is just creating unnecessary code.
In reality the problem is pretty much always that you have run the data through a mysql escape function before displaying it. Probably while you were in the process of saving it. Instead, escape the data for saving but display an unescaped version.
<?php echo str_replace('\r\n', "\r\n", $text_with_line_breaks); ?>
See single quotes & double quotes this is a trick.
A perfect solution for newbies.
you overdo quote in insert/update statement
This problem in you case you can solve doing next
<?php
$str = 'lin1\r\nlin2';
$solved_str = str_replace(array("\\r","\\n"), array("\r","\n"), $str);
var_dump($str,$solved_str);
But you need to check insert/update statement on over quotation escape symbols
I would recommend using double quotes for \r\n such as "\r\n". I've never had it work properly with single quotes.
For non- textarea use this function
function escapeNonTextarea($string){
$string=str_replace(array('\n','\r\n','\r'),array("<br>","<br","<br>"),$string);
return $string;
}
For text area use this function
function escapeTextarea($string){
$string=str_replace(array('\n','\r\n','\r'),array("\n","\r\n","\r"),$string);
return $string;
}
call appropriate function and pass argument
I am getting input from user on my site through a text area. the input may contain <a> TAG.
I want to extract the url from the input.
$res = get_magic_quotes_gpc() ? stripslashes($data) : $data;
$res = mysql_real_escape_string($res); // php 4.3 and higher
preg_match('#href\s*?=\s*?[\'"]?([^\'"]*)[\'"]?#i', $res, $captures);
$href = $captures[1];
example
if Input sting is this?
$data = 'any string Any Anchor';
the extracted output becomes
"\"http://www.example.com""
i checked the output after each line, 2 double quotes comes after
mysql_real_escape_string($res);
mysql_real_escape_string should only AND ALWAYS be used when passing user values into MySQL queries. Don't use it for anything else, use the right escaping function for the right task.
Here, I don't think you need to use an escape function at all. Your regular expression looks fine, I'm confident it will work if you remove the escaping function.
Also, don't use get_magic_quotes_gpc if you can avoid it. I could explain why but I suppose the fact that it's been deprecated since PHP5.0 is evidence enough. If your host does not allow you to disable it I would consider switching to a more savvy host.
Why don't you try processing the input using XPath to find the a elements and then extract the href attribute value. I did something similar and used XPath in order to process input and it worked a treat. Saves you having to write very complex regex expressions if you would like to account for other tags later on.
Hope this helps.
I have a form into which I entered a newline character which looked correct when I entered it, but when the data is now pulled from the database, instead of the white space, I get the \n\r string showing up.
I try to do this:
$hike_description = nl2br($hike_description);
But it doesn't work. Does anyone know how this can be fixed? I am using PHP.
And here is the page where this is happening. See the description section of the page:
http://www.comehike.com/hikes/scheduled_hike.php?hike_id=130
Thanks,
Alex
Does anyone know how this can be fixed?
Sure.
Your code doing unnecessary escaping, most likely before adding text to the database.
So, instead of replacing it back, you have to find that harmful code and get rid of it.
This means, you have probably plain text '\n\r' strings in the db.
Try to sanitize db output before display:
$sanitized_text = preg_replace('/\\[rn]/','', $text_from_db);
(just a guess).
Addendum:
Of course, as Col. Shrapnel pointed out, there's something fundamentally wrong
with the contents of the database (or, it is used this way by convention and you don't know that).
For now, you have fixed a symptom partially
but it would be much better to look for the reason for these escaped characters
being in the database at all.
Regards
rbo
You can use str_replace to clean up the input.
$hike_description = nl2br(str_replace("\r\n", "\n", $hike_description));
$hike_description = str_replace(array('\n','\r'),'',$hike_description);
You may want to read up on the differences between the single quote and double quote in PHP as well: http://php.net/manual/en/language.types.string.php
I am using tinyMCE and, rather annoyingly, it replaces all of my apostrophes with their HTML numeric equivalent. Now most of the time this isn't a problem but for some reason I am having a problem storing the apostrophe replacement. So i have to search through the string and replace them all. Any help would be much appreciated
did you try:
$string = str_replace("'", "<replacement>", $string);
Is it just apostrophes that you want decoded from HTML entities, or everything?
print html_entity_decode("Hello, that's an apostophe.", ENT_QUOTE);
will print
Hello, that's an apostrophe.
Why work around the problem when you can fix the cause? You can just turn of the TinyMCE entity encoding*. More info: here
*Unless you want all the other characters encoded, that is.