Replacing backslashes with two blackslashes [duplicate] - php

I came across a strange problem in my PHP programming. While using the backtrace function to get the last file the PHP compiler was working with. It would give it to me the path using backslashes. I wanted to store this string in the database, but MySQL would remove them; I'm assuming it was thinking I wanted to escape them.
So C:\Path\To\Filename.php would end up C:PathToFileName.php in the database. When I posted this question to Google, I found many others with the same problem but in many different situations. People always suggested something like:
$str = '\dada\dadda';
var_dump(str_replace('\', '\\', $str));
The problems with this is, even if you put it into a loop of some kind, is that you just keep replacing the first \ with \\. So it starts off like \ then \\\ then \\\\\ then \\\\\\\ then \\\\\\\\\ etc... Until it fills the memory buffer with this huge string.
My solution to this problem, if anyone else has it is:
//$file = C:\Path\To\Filename.php
//Need to use \\ so it ends up being \
$fileArray = explode("\\", $file);
//take the first one off the array
$file = array_shift($fileArray);
//go thru the rest of the array and add \\\\ then the next folder
foreach($fileArray as $folder){
$file .= "\\\\" . $folder;
}
echo $file
//This will give you C:\\Path\\To\\Filename.php
So when it's stored in the database, it will appear to be C:\Path\To\Filename.php.
If anyone else has a better solution to this, I'm all ears.

You need to "double escape" them inside preg_replace parameters (once for the string, once for the regex engine):
$mystring = 'c:\windows\system32\drivers\etc\hosts';
$escaped = preg_replace('/\\\\/','\\\\\\\\',$mystring);
echo "New string is: $escaped\n";
Or only once if you use str_replace:
$newstring = str_replace('\\','\\\\',$mystring);
echo "str_replace : $newstring\n";
?>

mysql_real_escape_string('C:\Path\To\Filename.php');

You can use regex capture group ():
echo preg_replace('/([\\\])/', '${1}${1}', "\b is a metasequence");
// 3 backslahses
// outputs: \\b is a metasequence

Stupid but works for me.
$BS='\\\';
(You put a double backslash in the $BS, but actually you get one backslash only.
$FullName = "C:".$BS.$BS."Path".$BS."To".$BS."FileName.php";
You should get the $FullName "C:\\Path\To\Filename.php"

Related

PHP How to output a string that comes after a certain keyword in a long text

Basically, I want to take a long text file (source code), find a specific keyword in that file, and then print out the next 400 characters that come after that keyword. I don't want every thing after the keyword because that ends up being 20,000+ characters.
If I could, I'd like to delimit them right there (which is what I tried to do originally but failed) It's becoming very confusing very quickly. If I can just get the 400 characters, then I can save that to a text file, and then delimit that 400 character text file.
My code now is:
<?php
$website = $_GET["website"]; //I'm pulling the website from a form
$contents = file_get_contents($website));
$del = 'keyword';
$search = preg_quote($del, '/');
$search = "/^.*$search.*\$/m";
if(preg_match_all($search, $contents, $found)){
echo implode("\n", $found[0]);
}else{}
?>
The problem is the above prints out EVERYthing after the keyword, and I can't even take what I get and delimit it further. I'm at the point where the more I come up with ideas the further I'm getting from the solution.
Any help is greatly appreciated.
You can use substr($your_string, 0, 400) to get only 400 characters starting from string.
Syntax for using this method is substr(string,start,length)
You can do this with a combination of strpos, strlen and substr. You don't need any regex to do this, and you should not use it because regex generally is slow as death. Avoid regex whenever possible, and only use it when you don't have any other answer.
<?php
$website = $_GET["website"]; //I'm pulling the website from a form
$contents = file_get_contents($website));
$del = 'keyword';
//get the index of the end of your split value
//this is the character index of your keyword, plus the length of the keyword,
//so it will start collecting the next bit at the end of the first occurance of keyword.
$index = strpos($contents, $del) + strlen($del);
//get the text you want
$text = substr($contents, $index, 400);

PHP Regex Replace

I have a string like <div><center>[content]</center></div>.
The "[content]" gets replaced by a php script that inserts a content from a database.
I've solved that problem by using the str_replace function. Now I want to modify my script like that: If I type [content] it should replace it. If I write [[content]] it shouldn't do anything. I thought about using regex but whatever I try -> It does not work.
If you don't understand me, just think back to c#, java,...: If I type \n, its a newline. If I type \n its "\n". I would be very thankfull if anyone could help.
Take a look at this example:
"aa[content]aa" -> aaMYCONTENTaa
"aa[[content]]aa" -> aa[[content]]aa
"aa[[[content]]]aa" -> aa[MYCONTENT]aa
Pure regex solution is possible, but you are heading on a dangerous path of building your own templating engine. There are several solutions available (smarty is the most popular one)
<?php
$str = preg_replace('([^\[]?)\[content\]([^\]]?)', '\1' . $yourcontent . '\2', $str);
?>
Explanation: [^\\[]? matches everything but the [ character, including nothing. This means [[content]] doesn't match.
EDIT:
the code will replace [content] with the $replace_content_with value unless it has [ before or ] after
$original = '<div><center>[content]</center></div>';
$replace_content_with = 'my new content';
$pattern = '/([^\[])\[content\]([^\]])/i';
$new_data = preg_replace($pattern, '\1'.$replace_content_with.'\2', $original);
echo $new_data; //print <div><center>my new content</center></div>
note that if your replacement content include \[SOME NUMBER] in it - it might not work as expected
Just replace '>[content]<' with '>whatever you want<'

How do I use "-----" in php string functions?

I have a form that I have to pull some strings out of. The form uses long dashed lines for dividing data sets. It would be handy to use:
strpos($string, "----")
and
$file2= explode("-----", $file1)
but they don't seem to work. I have replaced the "-" with "." and used "....." in the above to successfully extract the needed data, but it removes wanted dashes, such as 2-year-old, in the extracted data. So I'm back to wanting to use "----" in the code lines above.
I also tried to just replace "--" to ".." but the following doesn't work either.
$string = str_ireplace("--", "..",$string );
Any suggestions would be appreciated.
Thanks.
Is there a way to make this work?
This works perfectly fine.
<?php
$test = 'name----address----2-year-old----dob';
$test_chunks = explode("----", $test);
echo $test_chunks[2];
?>
Displays "2-year-old" w/o any issues. If you must convert the dashes to something else, try this as well:
test_convert = str_replace("----", "....", $test);
...and then explode using periods.

mysterious whitespace when putting a string togehter

This may seem odd but I'm simply trying to put a url together.
The first part ($first) I get from user input using strrpos() and substr() with "/".
The exact file I want to get to is fixed ($second) so all I think I need to do is this:
$first = "http://www.somedomain.de/somepath/";
$second = "thexml.xml";
$url = $first.$second;
BUT: Although I use trim() on every part there still is some whitespace between the two parts when I print $url.
When I try to navigate to $url the whitespace is replaced by a "%".
The path itself is correct, when I get rid of the whitespace/ % manually in my browser's adress bar.
I also tried putting the two strings together with an array and implode() but the output stays the same.
What am I doing wrong?
Update from Lisa
ok, so I printed $first and $second separately and there are no whitespaces. it seems to be appearing when I concatenate them and exactly where the two strings are put together.
Any other ideas?
ok, so I printed $first and $second separately and there are no whitespaces. it seems to be appearing when I concatenate them and exactly where the two strings are put together.
Any other ideas?
Most likely, the code you're editing or the inputs (user, database, etc.) is not what you expect. Try trimming down (no pun intended) the code to a minimal example. For example, go from
$first = "http://www.somedomain.de/somepath/";
$second = "thexml.xml";
$url = $first.$second;
echo $url; // No space
to
$first = $_POST['url'];
$second = "thexml.xml";
$url = $first.$second;
echo $url; // If this contains a space, the input contains the offending space
step-by-step to find the mistake.
Have you tried rawurlencode? http://php.net/rawurlencode
I know this is a very old question but I just had this similar issue and was finally able to find a solution.
My solution is to use the trim function like this:
$url = trim($first).$second;

How can I replace apostrophes while uploading a csv file?

I'm having trouble replacing apostrophes while uploading a csv file with a bunch of different descriptions.
Right now I have
$remarks = str_replace("'", "’", $data[28]);
This gives me an error starting with the first apostrophe that shows up in my file. That first phrase where the apostrophe appears ends in "'s". If I change it to
$remarks = str_replace("'s", "’", $data[28]);
it will go past that first problem and get to the next problem ('t).
What am I doing wrong? I'm new to php, and I'm sure this must be a simple solution...
array_map($data, function($a) { return(str_replace($a, "'", "’")) });
should walk all elements of the array and replace all quotes for you.
It looks like you're trying to re-invent the wheel. It looks like you're trying to parse the csv yourself. If you are stop it. You should be using str_getcsv and you won't have to worry about escaping anything.
After that, you'll probably want to look into preg_replace.
preg_replace( "#'\w?#g", '', $data[$index] );

Categories