I wanna accomplish something like this:
!say some message
which then is taken to a function, which proceeds with the content. As you can imagine, I'm listening on some text-inputs. Right now I'm facing the problem, that strings like this also trigger the case:
this is !say some text
Code:
$prefix = "!";
switch ($message->content) {
case preg_match("/[^.*]$prefix . 'say' (.*) /", $message->content):
_say($message);
break;
}
function _say($message)
{
$parts = explode("!say", $message->content);
return $message->channel->sendMessage(trim($parts[1]), true);
}
From my understanding, the regexp is correct (also confirmed on a regexp-tester).
Tested with substr as well, but that doesn't do it either.
case substr($message->content, 0, 3) == $prefix . 'say' :
What am I doing wrong?
A command is a command, it should not be something to be fooled around with. So instead of using regex I suggest a simple string comparison:
$prefix = "!";
function _say($message){
return $message->channel->sendMessage(trim($message), true);
}
if($message->content[0] == $prefix){
if($p = strpos($message->content, ' ') !== false){
$cmd = substr($message->content, 1, $p);
switch($cmd){
case 'say':
_say(substr($message->content, $p));
break;
default:
die('unknown command');
}
} else {
die('empty cmd');
}
} else {
die('no command');
}
Related
I've got 3 variables:
$left_side = "'Username'";
$equation = "==";
$right_side = "'Username'";
I want to test these variables as it was an if statement like so:
if($left_side $equation $right_side) {
// do something
} else {
// do something else
}
I know this works:
if(eval("return ".$left_side." ".$equation." ".$right_side.";")) {
// do something
} else {
// do something else
}
I always tought it's 'not good' to use eval. Especially when you try to run user input.
Is there an other way to do this? I tried to google it, but it's not my friend to day ;)
You may do something like this:
function testValues($val1, $equation, $val2) {
$res = false;
switch($equation) {
case "==":
$res = $val1 == $val2;
break;
case ">":
$res = $val1 > $val2;
break;
//....
default:
throw new Exception("Unknown operator");
}
return $res;
}
and than use it like:
if(testValues($left_side,$equation,$right_side)) {
//do something
} else {
//do something
}
eval is evil. And no, there's no other (easy) solution, but maybe this one helps:
if ($equation == "==") {
if ($left_side == $right_side) {
// ... your code goes here.
} else {
// Do some other stuff.
}
}
You could use switch:
$left_side = "'Username'";
$equation = "doublequal";
$right_side = "'Username'";
switch($equation){
case 'doublequal':
if ($left_side == $right_side) {
// code
}
break;
//......
}
You should never use eval() especially with user input.
eval() is evil, but call_user_func() is evil too and every framework uses this function in one place or another.
Tools aren't evil. They are just tools. Evil is the way that we use them.
As Uncle Ben said: Great power involves great responsibility :)
I find this trick
http://gonzalo123.com/2012/03/12/how-to-use-eval-without-using-eval-in-php/
the idea is create a temporary file with the PHP source code, include this file with the standard PHP’s include functions and destroy the temporary file.
I am writing what I thought would be a simple script but I am stuck.
The scenario is that I want to create 2 strings from the GET request.
eg: domain.com/script.php?Client=A12345
In script.php it needs to grab the "Client" and create 2 variables. One is $brand and needs to grab the A or B from the URL. The Other is $id which needs to grab the 12345 from the URL.
Now, after it has these 2 variables $brand and $id it needs to have an if statement to redirect based on the brand like below
if ($brand=="A") {
header('Location: http://a.com');
}
if ($brand=="B") {
header('Location: http://b.com');
At the end of each URL I want to apend the $id though and I am unsure on how to do this.
So for example I would access the script at domain.com/script?Client=A1234 and it needs to redirect me to a.com/12345
Thanks in advance!
$fullCode = $_REQUEST['Client'];
if(strpos($fullCode, 'A') !== false) {
$exp = explode('A',$fullcode);
header('Location: http://a.com/' . $exp[1]);
}
else if(strpos($fullCode, 'B') !== false) {
$exp = explode('B',$fullcode);
header('Location: http://b.com/' . $exp[1]);
}
else {
die('No letter occurence');
}
You can easily do,
$value = $_GET['Client'];
$brand = substr($value, 0, 1);
$rest = substr($value, 1, strlen($brand)-1);
now you have the first character in $brand string and you can do the if statement and redirect the way you want...
You mean like this?
Notice: this will only work if brand is just 1 character long. If that's not the case, please give better examples.
<?php
$client = $_GET['Client'];
$brand = strtolower(substr($client, 0, 1));
$id = substr($client, 1);
if ($brand == 'a')
{
header("Location: http://a.com/$id");
}
elseif ($brand == 'b')
{
header("Location: http://b.com/$id");
}
?>
Try using:
preg_match("/([A-Z])(\d*)/",$_GET['Client'],$matches);
$matches[1] will contain the letter and $matches[2] will contain your id.
Then you can use:
if ($matches[1]=="A")
{
header('Location: http://a.com/{$matches[2]}');
}
if ($matches[1]=="B")
{
header('Location: http://b.com/{$matches[2]}');
}
suggest you could also try
$requested = $_GET["Client"];
$domain = trim(preg_replace('/[^a-zA-Z]/',' ', $requested)); // replace non-alphabets with space
$brand = trim(preg_replace('/[a-zA-Z]/',' ', $requested)); // replace non-numerics with space
$redirect_url = 'http://' . $domain . '/' . $brand;
header('Location:' . $redirect_url);
but it'd be better if you could get the domain name and brand as two individual parameters and sanitize them individually before redirecting them to prevent the overhead of extracting them from a single parameter.
Note: this expression might be useless when the domain name itself has numerics and because the Client is obtained through get a good deal of validation and sanitation would be required in reality.
$brand = strtolower($_GET['Client'][0]);
$id = substr($_GET['Client'], 1);
header("Location: http://{$brand}.com/{$id}");
If for some purpose you want to use explode, then you need to have a separator.
Let's take '_' as the separator, so your example would be something like this: domain.com/script.php?Client=A_12345
$yourstring = explode("_",$_GET["Client"]);
echo $yourstring[0];
//will output A
echo $yourstring[1];
//will output 12345
//your simple controller could be something like this
switch($yourstring[0]){
case: 'A':
header('Location: http://a.com?id='.$yourstring[1]);
exit();
break;
case: 'B':
header('Location: http://b.com?id='.$yourstring[1]);
exit();
break;
default:
//etc
}
I have a html form with text input field. I'm wondering how to recognize specific input from the form. Example input commands:
<input type="text" name="action" value="bookmark http://google.com" />
<?php
if ($command == "goto"):
// go to website X
elseif ($command == "bookmark"):
// bookmark website X
else:
// something else
endif;
?>
I think the easiest way is to split the string on the first space to separate it into a command and the parameter for that command. The "2" parameter to explode() allows spaces to be used in $param, if necessary.
$input = explode(' ', $_POST['action'], 2);
$command = $input[0];
$param = $input[1];
switch ($command) {
case 'goto':
// go to website $param
break;
case 'bookmark':
// bookmark website $param
break;
default:
// unknown command
}
$aAct = explode(' ', $_POST['action');
if(is_array($aAct)) {
switch($aAct[0]) {
case 'bookmark':
/* do action e.g. header('Location: ' . $aAct[1]); */
break;
}
}
Make a case/break combination for every action you intend to specify..
Something like this?:
//get the command from your value
$command = current(explode(" ", $_POST['action']));
//get the url from your value
$url = next(explode(" ", $_POST['action']));
And as stated by karim79, a switch to handle the input would more appropriate.
switch($command) {
case 'goto':
// do stuff with $url;
break;
case 'bookmark':
// do stuff with $url;
break;
default: // do something default;
}
hope it helps
Try this:
$request = $_POST['action'];
$split = explode(' ',$request,2);
$command = $split[0];
if(!isset($split[1])){
//no url
die;
}
$url = $split[1];
if($command == "goto"){
header('location: '.$url);
die;
}elseif($command == "bookmark"){
header('location: '.$url);
die;
}else{
echo 'No Commands :(';
}
Use $_POST or $_GET to retrive the request data. ie: $_GET['action']
Set the header location to redirect the browser. die; or exit; is used to terminate and output the current script
After thinking about This Question and giving an answer to it I wanted to do more about that to train myself.
So I wrote a function which will calc the length of an given function. Th given php-file has to start at the beginning of the needed function.
Example: If the function is in a big phpfile with lots of functions, like
/* lots of functions */
function f_interesting($arg) {
/* function */
}
/* lots of other functions */
then $part3 of my function will require to begin like that (after the starting-{ of the interesting function):
/* function */
}
/* lots of other functions */
Now that's not the problem, but I would like to know if there are an cleaner or simplier ways to do this. Here's my function: (I already cleaned a lot of testing-echo-commands)
(The idea behind it is explained here)
function f_analysis ($part3) {
if(isset($part3)) {
$char_array = str_split($part3); //get array of chars
$end_key = false; //length of function
$depth = 0; //How much of unclosed '{'
$in_sstr = false; //is next char inside in ''-String?
$in_dstr = false; //is nect char inside an ""-String?
$in_sl_comment = false; //inside an //-comment?
$in_ml_comment = false; //inside an /* */-comment?
$may_comment = false; //was the last char an '/' which can start a comment?
$may_ml_comment_end = false; //was the last char an '*' which may end a /**/-comment?
foreach($char_array as $key=>$char) {
if($in_sstr) {
if ($char == "'") {
$in_sstr = false;
}
}
else if($in_dstr) {
if($char == '"') {
$in_dstr = false;
}
}
else if($in_sl_comment) {
if($char == "\n") {
$in_sl_comment = false;
}
}
else if($in_ml_comment) {
if($may_ml_comment_end) {
$may_ml_comment_end = false;
if($char == '/') {
$in_ml_comment = false;
}
}
if($char == '*') {
$may_ml_comment_end = true;
}
}
else if ($may_comment) {
if($char == '/') {
$in_sl_comment = true;
}
else if($char == '*') {
$in_ml_comment = true;
}
$may_comment = false;
}
else {
switch ($char) {
case '{':
$depth++;
break;
case '}':
$depth--;
break;
case '/':
$may_comment = true;
break;
case '"':
$in_dstr = true;
break;
case "'":
$in_sstr = true;
break;
}
}
if($depth < 0) {
$last_key = $key;
break;
}
}
} else echo '<br>$part3 of f_analysis not set!';
return ($last_key===false) ? false : $last_key+1; //will be false or the length of the function
}
Tokenizer (Example) - Learn it, love it.
You could probably reduce the number of state variables a little, but truthfully... yes, it will be messy code. I would probably get rid of $may_ml_comment_end and peek ahead for the next character when I encounter an asterisk, for example. You will need to rewrite your foreach loop to a regular for loop be able to do that without creating a bigger mess though.
PS: I don't see you handling the escape character yet. Without the above approach, that would introduce another boolean variable.
Another problem with your current code is that characters immediately following a / don't get interpreted as they should. However unlikely
echo 5/'2'; // NB: no space in between
is valid in PHP and would break your parser.
I need to find the value of a variable and use it to add a class to a div, based on a switch statement.
For example, my variable is $link and if $link has google.com IN IT at all, I need $class to equal 'google', if $link as yahoo.com IN IT at all, $class then needs to equal 'yahoo'
So, I need something like this, but I'm not sure how/or if to use preg_match or something to check and see if the $link variable has the value we are looking for in it - see 'case' text below:
switch ($link) {
case 'IF link has Google.com in it':
$class = 'google';
break;
case 'IF link has Yahoo.com in it':
$class = 'yahoo';
break;
default:
# code...
break;
}
OR if there is a better way to do this, please let me know :D
Also, I'm good with using an IF ELSE statement as well..
Thanks
You want an IF-statement, not a switch statement
I think preg_matchis not necessary here.stripos is enough for it.
$url = $link->hits;
$pos_google = stripos($url,'google.com');
$pos_yahoo = stripos($url,'yahoo.com');
if($pos_google !== false)
{
$class = 'google';
}
elseif($pos_yahoo !== false)
{
$class = 'yahoo';
}
else
{
#code
}
Seems it could be simpler:
if(ereg("google", $link)){
$class = "google";
}else if(ereg("yahoo", $link)){
$class = "yahoo";
}else{
$class = "";
}