PHP - Replace characters in a string
PHP - Replace characters in a string
I have read a number of articles on str_replace() on here and other resources, and not found the answer to my problem.
str_replace()
Here’s the string I have a problem with which is stored in $title ...
$title
Paul McCartney's Theme From The Film "The Honorary Consul”
Here’s the code I’m using ...
str_replace(‘“‘,’ ‘,$title);
str_replace(‘“‘,’ ‘,$title);
For some reason, the code above is completely ignoring this string, and a number of others similar.
I think it may be because of the Apostrophe as the above code works fine for strings which don’t have apostrophe’s as part of the text.
I need to keep the apostrophe in the title, but I’m not so worried about the “
However, if someone can suggest a way to keep both, in the same string, and add the whole string in a MySQL INSERT command string, that would be the best result for me.
MySQL INSERT
@tftd can you post an example?]
– Rich Starkie
Jun 30 at 22:51
@RichStarkie php.net/manual/en/pdo.prepared-statements.php
– Hyyan Abo Fakher
Jun 30 at 22:54
Possible duplicate of How can I prevent SQL injection in PHP?
– user3783243
Jul 1 at 2:23
The guys above have already posted more than enough. And because you might get confused at some point should you pdo
exec or execute - this is an extra bonus stackoverflow.com/questions/26849105/pdoexec-or-pdoexecute. :D– tftd
Jul 1 at 8:47
exec
execute
2 Answers
2
You can use PDO::quote
On php.net are good examples, just look on manual.
Try it this way:
$title = 'Paul McCartney's Theme From The Film "The Honorary Consul”';
str_replace('”',' ', $title);
Anyway, I would recommend you to use Prepared Statements to insert your data.
Follow this example: https://www.w3schools.com/php/php_mysql_prepared_statements.asp
I would escape the
’ if i could, but the $title variable comes from an API (from a highly trusted and well respected source)– Rich Starkie
Jun 30 at 23:04
’
$title
@RichStarkie what does var_dump($title) return? Probably it is already escaped.
– Reza Saadati
Jun 30 at 23:09
@RichStarkie ok, you don't need to escape it. Just use the second line of my code. You have been using the character
‘, which is wrong. It should be '.– Reza Saadati
Jun 30 at 23:15
‘
'
thats the command I'm already using, but its not working :( it appears the SO app doesn't translate
' properly :(– Rich Starkie
Jun 30 at 23:17
'
@RichStarkie So you don't have
” you have a ". But anyways don't fix that, this isn't the answer. Do it the right way, parameterize your query.– user3783243
Jul 1 at 2:24
”
"
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
USE PREPARED PDO STATEMENTS!!!! You don't need to worry about this with prepared statements. If you are not using them - you should start immediately as you probably are open to SQL injection.
– tftd
Jun 30 at 22:50