PHP variables look the same but are not equal (I'm confused) - php

OK, so I shave my head, but if I had hair I wouldn't need a razor because I'd have torn it all out tonight. It's gone 3am and what looked like a simple solution at 00:30 has become far from it.
Please see the code extract below..
$psusername = substr($list[$count],16);
if ($psusername == $psu_value){
$answer = "YES";
}
else {
$answer = "NO";
}
$psusername holds the value "normann" which is taken from a URL in a text based file (url.db)
$psu_value also holds the value "normann" which is retrieved from a cookie set on the user's computer (or a parameter in the browser address bar - URL).
However, and I'm sure you can guess my problem, the variable $answer contains "NO" from the test above.
All the PHP I know I've picked up from Google searches and you guys here, so I'm no expert, which is perhaps evident.
Maybe this is a schoolboy error, but I cannot figure out what I'm doing wrong. My assumption is that the data types differ. Ultimately, I want to compare the two variables and have a TRUE result when they contain the same information (i.e normann = normann).
So if you very clever fellows can point out why two variables echo what appears to be the same information but are in fact different, it'd be a very useful lesson for me and make my users very happy.

Do they echo the same thing when you do:
echo gettype($psusername) . '\n' . gettype($psu_value);

Since i can't see what data is stored in the array $list (and the index $count), I cannot suggest a full solution to yuor problem.
But i can suggest you to insert this code right before the if statement:
var_dump($psusername);
var_dump($psu_value);
and see why the two variables are not identical.
The var_dump function will output the content stored in the variable and the type (string, integer, array ec..), so you will figure out why the if statement is returning false

Since it looks like you have non-printable characters in your string, you can strip them out before the comparison. This will remove whatever is not printable in your character set:
$psusername = preg_replace("/[[:^print:]]/", "", $psusername);

0D 0A is a new line. The first is the carriage return (CR) character and the second is the new line (NL) character. They are also known as \r and \n.
You can just trim it off using trim().
$psusername = trim($psusername);
Or if it only occurs at the end of the string then rtrim() would do the job:
$psusername = rtrim($psusername);
If you are getting the values from the file using file() then you can pass FILE_IGNORE_NEW_LINES as the second argument, and that will remove the new line:
$contents = file('url.db', FILE_IGNORE_NEW_LINES);

I just want to thank all who responded. I realised after viewing my logfile the outputs in HEX format that it was the carriage return values causing the variables to mismatch and a I mentioned was able to resolve (trim) with the following code..
$psusername = preg_replace("/[^[:alnum:]]/u", '', $psusername);
I also know that the system within which the profiles and usernames are created allow both upper and lower case values to match, so I took the precaution of building that functionality into my code as an added measure of completeness.
And I'm happy to say, the code functions perfectly now.
Once again, thanks for your responses and suggestions.

Related

I am getting a error using php (str_replace)

I am getting a error while using php str_replace function.
I am reading out a string in a different file a JSON
and if I remove the str_replace part it works without the error but I want to make the ** go to bold if there are any other ways you know you can also just tell that.
<?php
$data = json_decode($readjson, true);
echo "<br/><br<br/>";
foreach ($data as $emp) {
echo str_replace("**","<strong>","$data"), $emp['message']."<br/>";
}
?>
And the output is
Notice: Array to string conversion in C:\Users\k-ver\Dropbox\Other\website stuff or smth\r3mind3r\changelog.php on line 16
Array - Weekley Update - Another great week at our side! We have made enournous advances in synching with the raspberry pi (the computer we are going to host from) and are closer than ever to our promised release We have also been fixing on the mute commands and are very close to making it work, aswell with unmute command.language feature is closing up on complete and about 70% of the bot has the language system working. We also made a new system that should be easier to use for bouth us devs and the translators. All thats left for the release atm is: -finishing synching -fixing the mute command and unmute command -make a functioning permissonlevel system -adding those last 30% of the bot that does not have the translationsystem in place. and the bot will have its huge release! (about time if you asked me)
(it is for a dev log)
and the part I don't understand is the notice and I also don't understand how to fix it
It would be awesome if you guys would like to help me.
This variable should be string value e.g $emp['message'] not the multi-dimensional array $data.
// see this line with $emp['message'] not $data array
str_replace("**","<strong>",$emp['message']);
EDIT: As per comment
<?php
$string = '{
"188762891137056769": {
"message": "\n**- Weekley Update -**\nAnother great week at our side! \nWe have made enournous advances in synching with the raspberry pi *(the computer we are going to host from)* and are closer than ever to our promised release\n\nWe have also been fixing on the mute commands and are very close to making it work, aswell with unmute command.language feature is closing \nup on complete and about 70% of the bot has the language system working. We also made a new system that should be easier to use for bouth \nus devs and the translators.\n\n**All thats left for the release atm is:**\n-finishing synching \n-fixing the mute command and unmute command \n-make a functioning permissonlevel system\n-adding those last 30% of the bot that does not have the translationsystem in place. \n\nand the bot will have its huge release! *(about time if you asked me)*"
}
}';
$array = json_decode($string,1);
$message = $array['188762891137056769']['message'];
$re = '/\*\*(.*?)\*\*/m';
$subst = '<strong>$1</strong>';
echo preg_replace($re, $subst, $message);
?>
DEMO: https://3v4l.org/ovhGq
You used array inside str_replace("**","","$data") this is wrong, how you can fix it just replace $data with $emp
Your code is:
foreach ($data as $emp) {
echo str_replace("**","<strong>","$data"), $emp['message']."<br/>";
}
You see $data is an array, an $emp is the current element within the foreach loop.
So, you should do: str_replace("", "", $emp)
By the way, I see this: $emp['message'], which means $emp is an array too?
Maybe you should post the $readjson variable, so we'll know what type of data is.
If you want to enclose the text between ** with <strong></strong>, you need to use a regex. Here is a little code that does what you want :
function boldify($text) {
return preg_replace('/\*\*((.|\n|\r)*)\*\*/imU', '<strong>$1</strong>', $text);
}
Basically, it uses the function preg_replace to replace according to the regex (the first parameter).
How does this regex work :
1) You have \*\* at the beginning because that's your "opening tag". (* is a special regex character, so it needs escaping.)
2) You have ((.|\n|\r)*).
The inner part : .|\n|\r says "Catch me any character (the .) or (the |) a line feed (the \n) or a carriage return (the \r).".
Then you have the inner part enclosed with (inner part)*. This says "Match the inner part any number of time.".
Finally, you have the "middle part" enclosed with (middle part). This says "Remember what you just caught inside the parentheses, we will need it for the replace.
3) You have \*\* again.
4) All this is enclosed by /regex/imU.
The / are just there to say where the regex actually is.
The imU are flags: i is ignore case, m multiline, U ungreedy.
i are m are pretty straightforward, but U says "catch the smallest group possible".
As the second parameter you have '<strong>$1</strong>'. $1 is the group we remember from 2).
The third parameter is the subject.
I hope it was clear.
You can just use it like this :
echo boldify($emp['message']);

delete all bug string between two words

I've got a script which generates text. I need to be strip all repeated blocks of text. The string is in xml format, so I can use the beginning and ending tags to determine where the strings are. I've been using substr_replace to remove the unnecessary text... However, this only works if I know how many times said text is going to be present in the string. Example :
<container>
<string1>This is the first string.</string>
<string2>This is the second string.</string>
<stuff>This is the important stuff.</stuff>
</container>
That container might appear once, twice six times, seven times, whatever. The point is, it's necessary to only have it appear once in the string variable. Right now this is what I'm doing.
$where_begin = strpos($wsman_output,'<container');
$where_end = strpos($wsman_output,"</container>");
$end_length = strlen("</Envelope>");
$attack = $where_end - $where_begin;
$attack = $attack + $end_length;
$wsman_output = substr_replace($wsman_output,"",$where_begin,$attack);
And I do that for each time the container exists.... However, I just found out that it's not always going to be the same.. Which really messes things up.
Any ideas?
In the end I decided to use the method suggested here.
I pulled each block of string I wanted from the variable, then combined them back together in the required order.

str_replace URL space

I'm making a website where im alowing my users (after that they are loged in) to Add a (car) advertisement!
I have a form where the user can submit his car information.(add-vehicle.php)
Now I want to display each new advertisement in my list-view. (car-list.php)
How can I do this?
Use urlencode /urldecode to pass variables in url's urlencode
I recommand to use urlencode('string')
and then later when get your variable with urldecode('string')
Response to your comment:
if (isset($_GET['merk'],$_GET['car_id'],$_GET['titel']) === true )
{
$merk = urldecode(trim ($_GET['merk']));
$car_id = urldecode(trim($_GET['car_id']));
$titel = urldecode(trim($_GET['titel']));
}
You're changing a space into a hyphen. If it is stored in the database as a space, it will never find it because "This Entry" is different from "This-Entry". As others said, urlencode will work better, but if you still want to replace the space with a hyphen, just make sure that it is done the same in the database as well.
First, nobody in this world will know what you have in your database to tell what's the problem! At least post an example data.
Second, you must be sure of what you have and what you are comparing to.
You are basically asking if a is equal to b and to be fair that's something that you should be able to tell if you're programming!
Third, you should implement a methodology that allows you to quickly test your code, and that's from printing your data to the browser to a fully automated test.

PHP/MySQL: Strange output issue when echoing variable from MySQL database

I have a MySQL table that contains names and e-mail addresses. The data was originally imported from a .csv file, and it did not originally contain complete e-mail addresses. We had to append the #place.domain to the user's alias.
When the data is sitting in the MySQL table, it looks normal: person#place.domain; however, when I output the content in PHP, I get this: person #place.domain. There's always a space between the person and the #. It doesn't look like that in the MySQL column, nor does it look like that when I copy/paste the data into Notepad, Word, Excel, etc. Furthermore, if I erase the data in the column and manually replace it with person#place.domain, it displays normally in my PHP app. So I'm guessing there's some hidden character that PHP is picking up that I can't detect. Is there a way for me to clean this up? I've tried TRIM(), REPLACE,(), etc., all to no avail.
UPDATE: I've discovered that, when I click in the MySQL field and move among the characters using my arrow keys, I have to hit the arrow key TWICE to move past the # symbol, yet there is no visible space.
I made this sample code for you:
<?php
$test = "user #mail.com";
$aux = explode("#",$test);
$mailok = trim($aux[0])."#".trim($aux[1]);
echo $test." vs ".$mailok;
?>
This is likely something like non-breaking space (ascii 160). To get rid of it:
UPDATE my_table SET e_mail = REPLACE(e_mail, CHAR(160), '');
Try with a foreach cycle, and do the chr($char) function to every character in the string, it will display you the ascii code of each character in the string, and you will find the wrong character. It's the only solution I found. Hope to be useful

Why is constructing a URL with a mysql entry in PHP giving me a different String?

I'm writing some code to look at PTO assignment data, and noticed a strange problem where the URL didn't work when I generated it from my database entry, but did work when I entered the same string manually. When I echo them both strings look the same exactly, but when I equate them they are different. Is there some kind of hidden character or something with the encoding I can't see, and if so how do I fix it? I'm running the code using WAMPSERVER.
$pto = "assignments.uspto.gov/assignments/q?db=pat&reel=";
$row = mysql_fetch_assoc($result);
$ReelFrame = $row['ReelFrame']; // Should be "007358/0006" and looks to be correct.
$reelframearray = explode("/",$ReelFrame);
$gourla = $pto . $reelframearray[0] . "&frame=". $reelframearray[1];
$gourl = "assignments.uspto.gov/assignments/q?db=pat&reel=007358&frame=0006";
echo "$gourla <br>";
echo "$gourl <br>";
if ($gourl === $gourla){
echo "same string";
} else {
echo "different";
}
This is what the results look like:
assignments.uspto.gov/assignments/q?db=pat&reel=007358&frame=0006
assignments.uspto.gov/assignments/q?db=pat&reel=007358&frame=0006
different
I've narrowed it down to the mysql entry since replacing that with this:
$ReelFrame = "007358/0006";
Makes the strings the same.
Thanks for any help. The column for ReelFrame is a VARCHAR if that makes any difference.
please try to var_dump() your both variables instead of echoing them - maybe there are some leading/trailing whitespaces, linebreaks or something like that.
EDIT: just as a note: you realy shouldn't save multiple values in one database-coumn. if ReelFrame consits of two values, make two colums out of it: Reel and Frame - and don't use charchar for this, it looks like they should be ints (and that will avoid you from saving whitespaces linebreaks or something like that accidentally)
The first thought that comes to my mind is \n character.
Try this:
$ReelFrame = trim($row['ReelFrame']);
I tried the trim() suggestion, but it doesn't seem to work. I'm not sure what kind of character it is inserting, but I guess trim isn't removing it.
I just tried the var_dump, and it does show the strings are different lengths though nothing else looks different.
vardump of a ReelFrame entity compared with manual string:
string(20) "007358/0006"
string(11) "007358/0006"
likewise for the final string:
string(81) "assignments.uspto.gov/assignments/q?db=pat&reel=007358&frame=0006"
string(72) "assignments.uspto.gov/assignments/q?db=pat&reel=007358&frame=0006"
trim() doesn't seem to make any difference on the entity so it's still showing 20.
Are there any other invisible characters that trim might miss?

Categories