I've looked around on here quite a bit for an answer to my problem but I can't seem to find anything that helps. I'm building an Android application that needs to access student classes through a php script on the server. Each class is made up of a subject, subject number, and section number stored in a mysql database. I send the subject and subject number separated by a '\n' character ("subject\nnumber") to the php script so that it can find and return all sections under that course. Here's the code my script runs:
$course = explode('\n', $_REQUEST['course']);
$sections=mysql_query("select section from class where subj = '".$course[0]."' and number = '".$course[1]."' order by section");
while($e=mysql_fetch_assoc($sections))
$output[]=$e;
print(json_encode($output));
When I pass in the subject and number through my browser with something like
getSections.php?course=CS\n101
It properly formats it into a JSON string and it works perfectly. But when I try to use it with my app, I get an undefined offset: 1 error at line 2. I've wrapped the input string in other characters to make sure that it was sending the same thing as what I try in my browser and it is. It's really boggling my mind why it's not working the way it should.
It's also saying that $output is undefined but I'm pretty sure that's because the while loop is failing.
Any help would be greatly appreciated.
You need to use double quotes for the explode \n ~ explode("\n", $_REQUEST['course']);
Escape characters like newline (\n) only work in double quotes:
echo '\n' prints \n
whereas echo "\n" will print a new line
Related
UPDATE !!!
It seems that the website I used to test my code has issues and therefore I had problem with executing my thing. I still leave this post up, so someone else, with similar problem can learn something.
website to avoid: http://phptester.net
ORIGINAL POST !!!
I want to add a string to my variable that uses a double qouted word. Is that possible? I only get error.
FATAL ERROR syntax error, unexpected 'Old' (T_STRING) on line number 4
Here is the code:
<?php
$var = "name: ";
$biography = "\n I'm Robert and I came from \"Old\" Europe.";
echo $biography;
?>
I was checking it on this website:
http://phptester.net
It must be smg to do with the new line character in the beginning, or perhaps its not even possible to add double qouted words to a variable. I am not sure.
Your help is greatly appreciated !
I've tried many tests to make this work but can't seem to figure this one out!
A PHP code is called before it sends an email, it checks if placeholders have values in them, then adds them in email. Results I get are all on same line with no line breaks.
Can someone please tell me how to insert a line break in the code?
I've tried the linebreak br with single quotes and double in many places in the code, nothing is working. I've tried the echo code, I get errors.
Each placeholder starts with the IF statement and must end with the value}'; for each one. Where and how can I insert the line break between the IF and value}'; for each?
Thanks a million!
Results come out like this scapbooking20dancing35
instead of:
scapbooking
20
dancing
35
if you guys had to put a line break in this code, how does it go? cheers if($_POST['form']['age'] != '') $modAdminEmailText .= '{age:caption}: {age:value}';
/* Retrieve the admin email text */
$modAdminEmailText = $form->AdminEmailText;
/*Checks if the field has a value and if so, add it to the Email Text*/
if($_POST['form']['hobby'] != '')
$modAdminEmailText .= '{hobby:caption}: {hobby:value}';
if($_POST['form']['age'] != '')
$modAdminEmailText .= '{age:caption}: {age:value}';
/*After the field placeholders are added we will need to replace them with the actual submitted values.*/
$adminEmail['text'] = $modAdminEmailText;
$adminEmail['text'] = str_replace($placeholders, $values, $adminEmail['text']);
been there, done that. Here's what I think is going on.
I've tried the linebreak br ... with single quotes and double.. in many many places in the code, nothing is working.. I've tried the echo code, I get errors, 2 days now no sleep :(
using <br> in your code will only work if you write the e-mail as HTML. Check the documentation for the e-mail library you use to see how you do that.
Now in stead of using <br> you may want to use the \n or \r\n symbol. Beware, that if you use that, then you must enclose your string with double quotes: $somevar."\n"
Alternatively try to use PHP_EOL like this: $somevar. PHP_EOL
I'm not sure how these two methods behave when using string interpolation, but it's worth a try.
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']);
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.
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