I am trying to replace ' for '' in php, help please - php

I am trying to replace all ' matched in one string in php but I dont understabnd why it is not working this. I am newer in php.
the instruction is :
$val = "Hello I'm newer in PHP.";
$val = str_replace("'", "''", $val);
I tried to set backslah before and it is not working too
Could you help me please?

What you want is to make your string "db-safe". You have several options here:
Use mysql_real_escape_string if you're using the "old-school" mysql drivers (mysql_connect):
$str = mysql_real_escape_string("I'm newer to PHP");
Use PDO::quote() if your are using PDO:
$conn = new PDO(....);
$str = $conn->quote("I'm newer to PHP");
use prepared statements to insert / update tables (see http://php.net/manual/de/mysqli.quickstart.prepared-statements.php).
Personally I would prefer prepared statements, as it would also speed up your queries if you do multiple inserts/updates, and is the safest way.

Apart from a missing semicolon at the end of your first line, there's nothing wrong with the code you've written:
$val = "Hello I'm newer in PHP.";
$val = str_replace("'", "''", $val);
echo $val; // Hello I''m newer in PHP.

Related

I need to get sentences with some specifications from some text files and then store them into database

I have text that consist of some sentences. I have to parse the sentences that separated by dot and count words in every sentence. The sentences that contain more than 5 words will be inserted into database. here's my code :
<?php
require_once 'conf/conf.php';// connect to database
function saveContent ($text) {
//I have to get every sentence without lose the dot
$text1 = str_replace('.', ".dot", $text);
$text2 = explode ('dot',$text1);
//Text that contain ' cannot be inserted to database, so i need to remove it
$text3 = str_replace("'", "", $text2);
//Selecting the sentence that only consist of more than words
for ($i=0;$i<count($text3);$i++){
if(count(explode(" ", $text3[$i]))>5){
$save = $text3[$i];
$q0 = mysql_query("INSERT INTO tbdocument VALUES('','$files','".$save."','','','') ");
}
}
}
$text= "I have some text files in my folder. I get them from extraction process of pdf journals files into txt files. here's my code";
$a = saveContent($text);
?>
The result is only 1 sentence (the first sentence) that can be inserted in database.
I need your help, thank you so much : )
There are many ways to improve this (and to make it work correctly).
Rather than replace . with .dot, you can simply explode on the . and remember to replace it later. However, what if your sentence is something like Mr. Smith went to Washington.? You can't differentiate those periods with much reliability.
The variable $files in your INSERT is not defined in scope of this function. We don't know where it comes from or what you expect it to contain, but here, it will be NULL.
function saveContent ($text) {
// Just explode on the . and replace it later...
$sentences = explode(".", $text);
// Don't remove single quotes. They'll be properly escaped later...
// Rather than an incremental loop, use a proper foreach loop:
foreach ($sentences as $sentence) {
// Using preg_split() instead of explode() in case there are multiple spaces in sequence
if (count(preg_split('/\s+/', $sentence)) > 5) {
// Escape and insert
// And add the . back onto it
$save = mysql_real_escape_string($sentence) . ".";
// $files is not defined in scope of this function!
$q = mysql_query("INSERT INTO tbdocument VALUES('', '$files', '$sentence', '', '', '')");
// Don't forget to check for errors.
if (!$q) {
echo mysql_error();
}
}
}
}
In the long run, consider moving away from the mysql_*() functions and begin learning an API which supports prepared statements such as PDO or MySQLi. The old mysql_*() functions are soon to be deprecated and lack the security offered by prepared statements.

PHP Preg_Replace REGEX BB-Code

So I have created this function in PHP to output text in the required form. It is a simple BB-Code system. I have cut out the other BB-Codes from it to keep it shorter (Around 15 cut out)
My issue is the final one [title=blue]Test[/title] (Test data) does not work. It outputs exactly the same. I have tried 4-5 different versions of the REGEX code and nothing has changed it.
Does anyone know where I am going wrong or how to fix it?
function bbcode_format($str){
$str = htmlentities($str);
$format_search = array(
'#\[b\](.*?)\[/b\]#is',
'#\[title=(.*?)\](.*?)\[/title\]#i'
);
$format_replace = array(
'<strong>$1</strong>',
'<div class="box_header" id="$1"><center>$2</center></div>'
);
$str = preg_replace($format_search, $format_replace, $str);
$str = nl2br($str);
return $str;
}
Change the delimiter # to /. And change "/[/b\]" to "\[\/b\]". You need to escape the "/" since you need it as literal character.
Maybe the "array()" should use brackets: "array[]".
Note: I borrowed the answer from here: Convert BBcode to HTML using JavaScript/jQuery
Edit: I forgot that "/" isn't a metacharacter so I edited the answer accordingly.
Update: I wasn't able to make it work with function, but this one works. See the comments. (I used the fiddle on the accepted answer for testing from the question I linked above. You may do so also.) Please note that this is JavaScript. You had PHP code in your question. (I can't help you with PHP code at least for awhile.)
$str = 'this is a [b]bolded[/b], [title=xyz xyz]Title of something[/title]';
//doesn't work (PHP function)
//$str = htmlentities($str);
//notes: lose the single quotes
//lose the text "array" and use brackets
//don't know what "ig" means but doesn't work without them
$format_search = [
/\[b\](.*?)\[\/b\]/ig,
/\[title=(.*?)\](.*?)\[\/title\]/ig
];
$format_replace = [
'<strong>$1</strong>',
'<div class="box_header" id="$1"><center>$2</center></div>'
];
// Perform the actual conversion
for (var i =0;i<$format_search.length;i++) {
$str = $str.replace($format_search[i], $format_replace[i]);
}
//place the formatted string somewhere
document.getElementById('output_area').innerHTML=$str;
​
Update2: Now with PHP... (Sorry, you have to format the $replacements to your liking. I just added some tags and text to demostrate the changes.) If there's still trouble with the "title", see what kind of text you are trying to format. I made the title "=" optional with ? so it should work properly work texts like: "[title=id with one or more words]Title with id[/title]" and "[title]Title without id[/title]. Not sure thought if the id attribute is allowed to have spaces, I guess not: http://reference.sitepoint.com/html/core-attributes/id.
$str = '[title=title id]Title text[/title] No style, [b]Bold[/b], [i]emphasis[/i], no style.';
//try without this if there's trouble
$str = htmlentities($str);
//"#" works as delimiter in PHP (not sure abut JS) so no need to escape the "/" with a "\"
$patterns = array();
$patterns = array(
'#\[b\](.*?)\[/b\]#',
'#\[i\](.*?)\[/i\]#', //delete this row if you don't neet emphasis style
'#\[title=?(.*?)\](.*?)\[/title\]#'
);
$replacements = array();
$replacements = array(
'<strong>$1</strong>',
'<em>$1</em>', // delete this row if you don't need emphasis style
'<h1 id="$1">$2</h1>'
);
//perform the conversion
$str = preg_replace($patterns, $replacements, $str);
echo $str;

How can I remove slashes from strings?

I am trying to do some PHP programming concepts and I am not aware of some in-build functions. So my doubt is:
In PHP, how to remove slashes from strings? Is there any function available in PHP for this??
e.g.
$string="people are using Iphone/'s instead of Android phone/'s";
You can do a number of things here, but the two approaches I would choose from are:
Use str_replace():
$string = "people are using Iphone/'s instead of Android phone/'s";
$result = str_replace('/','',$string);
echo $result;
// Output: people are using Iphone's instead of Android phone's
If the slashes are backward slashes (as they probably are), you can use stripslashes():
$string = "people are using Iphone\\'s instead of Android phone\\'s";
$result = stripslashes($string);
echo $result;
// Output: people are using Iphone's instead of Android phone's
backslashes need escaping
$newstr = "<h1>Hello \ fred</h1>";
echo str_replace('\\','',$newstr);
If it is a quoted string. Use stripslashes
Heres what I use
function removeSlashes($string = '')
{
return stripslashes(str_replace('/', '', $string));
}
Test
echo $this->removeSlashes('asdasd/asd/asd//as/d/asdzfdzdzd\\hd\h\d\h\dw');
Output
asdasdasdasdasdasdzfdzdzdhdhdhdw
you can use function like
$string = preg_replace ("~/~", "", $string);
Use varian preg
$string="people are using Iphone/'s instead of Android phone/'s";
echo $string = preg_replace('/\//', '', $string);
body, html, iframe {
width: 100% ;
height: 100% ;
overflow: hidden ;
}
<iframe src="https://ideone.com/uIBINP" ></iframe>
I tried this method to remove single forward slashes.
I used str_replace to strip the slashes out. It still did not work for me, I had to go and change all the double quotes in the database to single quotes, update the table, then change it back to double quotes for it to work. Weird.
str_replace('\\', '', $content)
You can use stripslashes() function.
<?php
$str = "Is your name O\'reilly?";
// Outputs: Is your name O'reilly?
echo stripslashes($str);
?>

multiple preg_replace on the same variable

While delving into some old code I've stumbled upon a function which is used to clean up special characters using preg_replace very excessively. Unfortunatly there's no way to avoid this cleanup, the messed up data arrive from outside.
/* Example 1: current code */
$item = preg_replace('/' . chr(196) . '/',chr(142),$item);
$item = preg_replace('/' . chr(214) . '/',chr(153),$item);
$item = preg_replace('/' . chr(220) . '/',chr(154),$item);
Alot of those lines are in there, and all do the same (using different characters), so there should be a better way to do this. My first iteration to optimize this would be to use an indexed array, like this:
/* Example 2: slightly optimized code */
$patterns = array();
$patterns[0] = '/'.chr(196).'/';
$patterns[1] = '/'.chr(214).'/';
$patterns[2] = '/'.chr(220).'/';
$reps = array();
$reps[0] = chr(142);
$reps[1] = chr(153);
$reps[2] = chr(154);
$item = preg_replace($patterns,$reps,$item);
It does the job, but I guess there's somewhere a better and/or faster way of doing this alot easier and smarter - maybe even without preg_replace. Due to the early morning and/or the lack of good coffee, I was unable to find it myself so far.
Any suggestions?
As far as you're concerned to replace characters, you can make use of strtrDocs which has a nice array parameter:
$map = array(
chr(196) => chr(142),
chr(214) => chr(153),
chr(220) => chr(154),
);
$item = strtr($item, $map);
I think you could use str_replace for this use. Not sure about the characters you're replacing tho. But if str_replace works, it'll be a lot faster than those preg_replace.
But, does those lines slow your application too much or is it just a case of seeing something you could clean up? Because if it is, don't forget to prepare enough tests to avoid creating problems.
You should use strtr here.
$item = strtr($item, chr(196) . chr(214), chr(142) . chr(153));
http://php.net/manual/en/function.strtr.php
You need not regexp to this operation(replacing constant string to another), str_replace enough for you here. Besides, str_replace allows to replace array by array as you want
preg_replace or str_replace will both be slower than strtr which is designed for exactly this purpose.
echo strtr("This is a test","aiu","AIU");
will give
ThIs Is A test

sprintf and % signs in text

A problem I recently ran into was that when trying to update a field in my database using this code would not work. I traced it back to having a % sign in the text being updated ($note, then $note_escaped)... Inserting it with sprintf worked fine though.
Should I not be using sprintf for updates, or should it be formed differently?
I did some searching but couldn't come up with anything.
$id = mysql_real_escape_string($id);
$note_escaped = mysql_real_escape_string($note);
$editedby = mysql_real_escape_string($author);
$editdate = mysql_real_escape_string($date);
//insert info from form into database
$query= sprintf("UPDATE notes_$suffix SET note='$note_escaped', editedby='$editedby', editdate='$editdate' WHERE id='$id' LIMIT 1");
You are using sprintf totally wrong. Removing the function call in your code would still do the same thing. It should be:
sprintf("UPDATE notes_%s SET note='%s', editedby='%s', editdate='%s' WHERE id=%d LIMIT 1", $suffix, $note_escaped, $editedby, $editdate, $id);
You should read the manual.
first of all you should be using prepared statements instead of a sprintf-call
but if you absolutely have to do it this way you have to use:
$id = mysql_real_escape_string($id);
$note_escaped = mysql_real_escape_string($note);
$editedby = mysql_real_escape_string($author);
$editdate = mysql_real_escape_string($date);
//insert info from form into database
$query= sprintf("
UPDATE notes_%s /* this is still open for injection, and cannot be properly escaped with mysql_real_escape_string */
SET note='%s',
editedby='%s',
editdate='%s'
WHERE id='%d'
LIMIT 1",
$suffix,
$note_escaped, $editedby, $editdate, $id);
You can escape the % in the source text by replacing it with \% in mysql.
sprintf() is not used much in PHP, unless you need to format data somehow. These two statements work identically in PHP:
$num = 42;
$char = 'q';
$text = sprintf('The number is %d and the character is %s', $num, $char);
$text = "The number is $num and the character is $char";
sprintf's used more in C for "printing" variable data into a string. But PHP can already do that with double-quoted strings, so unless you need to use sprintf's special formatting functions (e.g. %0.2f for a 2-decimal-place float), it's easier to use the regular string method.
From http://php.net/manual/en/function.mysql-real-escape-string.php:
Note: mysql_real_escape_string() does not escape % and _. These are wildcards in MySQL if combined with LIKE, GRANT, or REVOKE.
You need to manually escape the % and _ if any with \% and _. I don't recommend using sprintf, but just improving your escape function.

Categories