mysterious whitespace when putting a string togehter - php

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;

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);

Replacing backslashes with two blackslashes [duplicate]

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"

str_replace doesn't seems to work with the implode function

After imploding an array:
$in_list = "'".implode("','",$array)."'";
$in_list content is :
'Robert','Emmanuel','José','Alexander'
Now when i try to replace the word José by another string,
str_replace("José","J",$in_list);
It doesn't get the new value, José is still there. Am i missing something? thanx in advance.
How exactly do you try to replace the string?
When trying it this way:
$in_list = str_replace("José","J",$in_list);
echo $in_list;
everything should work fine.
Remember, the function is returning a value. So it returns a new string.
This should work. It depends on your array.
$str = array('Robert','Emmanuel','José','Alexander');
$str = implode(",", $str);
print str_replace('José', 'J', $str);
I'm not sure what's going on, It seems to work for me. What version of PHP are you using?
$in_list = "'".implode("','", array('Robert', 'Emmanuel', 'José', 'Alexander'))."'";
$replaced = str_replace("José", "J", $in_list);
//prints 'Robert','Emmanuel','J','Alexander'
echo $replaced;
See: http://codepad.viper-7.com/24qutm
try $in_list = html_entity_decode((str_replace(htmlentities("José"),"J",htmlentities($in_list));
Have you tried on a word without accents? I would say you have a character set mismatch, for example 'José' in $in_list is in latin1 character set and your PHP source file in UTF8.
If this is the case, you should first convert either your PHP file or the variable to the character set you want to work with.
Spontaneous guess: Those two strings are not the same. I suppose one "José" is a string hardcoded in your source code and the other is received from the database or the browser or so. If the encoding of the two strings is not the same, PHP won't identify them as identical and not replace the character. Make sure your source code file is saved in the same encoding as the data you're working on, preferably both being UTF-8.
This worked for me, but it doesn't look like I'm doing anything notably different from you?
$array = array('Robert', 'Emmanuel', 'José', 'Alexander');
$in_list = "'".implode("','",$array)."'";
echo $in_list.PHP_EOL;
echo str_replace("José","J",$in_list).PHP_EOL;
Output:
'Robert','Emmanuel','José','Alexander'
'Robert','Emmanuel','J','Alexander'
Keep in mind that str_replace will not perform the replacement on $in_list itself, but rather return a string containing the replacement.
Hope this helps!

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.

PHP str_replace not working correctly

I'm using str_replace and it's not working correctly.
I have a text area, which input is sent with a form. When the data is received by the server, I want to change the new lines to ",".
$teams = $_GET["teams"];
$teams = str_replace("\n",",",$teams);
echo $teams;
Strangely, I receive the following result
Chelsea
,real
,Barcelona
instead of Chealsea,real,Barcelona.
What's wrong?
To expand on Waage's response, you could use an array to replace both sets of characters
$teams = str_replace(array("\r\n", "\n"),",",$teams);
echo $teams;
This should handle both items properly, as a single \n is valid and would not get caught if you were just replacing \r\n
Try replacing "\r\n" instead of just "\n"
I would trim the text and replace all consecutive CR/LF characters with a comma:
$text = preg_replace('/[\r\n]+/', ',', trim($text))
I had the same issue but found a different answer so thought I would share in case it helps someone.
The problem I had was that I wanted to replace \n with <br/> for printing in HTML. The simple change I had to make was to escape the backslash in str_replace("\n","<br>",($text)) like this:
str_replace("\\n","<br>",($text))

Categories