I'm not sure where is my problem. I've a script called with parameters (GET) like :
http://www.xxx.com?isms_restemsg=STOP&value=1
Here is my code :
$keyword_allowed = array("STOP", "");
$found_keyword = "N";
$keyword_cf = "";
for($i=0; $i < 2; $i++)
{
if (eregi($keyword_allowed[$i], $_GET["isms_restemsg"]))
{
$found_keyword = "Y";
$keyword_cf = $keyword_allowed[$i];
}
}
QUESTION : what happend when the url invoked is :
http://www.xxx.com?isms_restemsg=&value=1
In this case, what happend at the eregi instruction.
I'm asking this question because the $found_keyword="N", it should be "Y" Or is there an error ?
If yes can you help me ?
eregi is depreciated as of php 5.
Use stristr instead
if (stristr($keyword_allowed[$i], $_GET["isms_restemsg"]))
Or better yet, array_search
$keyword_allowed = array("STOP", "");
$found_keyword = "N";
if(($keyword_c = array_search($_GET["isms_restemsg"], $keyword_allowed)) !== false) {
$found_keyword = "Y";
}
You shouldn't use eregi(), since it's deprecated.
It doesn't even look as if you need regular expressions after all.
Give it a try with stristr() or even simple compare syntax:
if ($keyword_allowed[$i] == $_GET["isms_restemsg"])
(If you write this yourself you probably have control over the GET values as well.)
You can help yourself in such cases by echoing some debug output:
print_r($_GET);
for($i=0; $i < 2; $i++)
{
echo eregi($keyword_allowed[$i], $_GET["isms_restemsg"]));
}
When the URL is like this
http://www.xxx.com?isms_restemsg=&value=1
Your $_GET["isms_restemsg"] is blank
hence if (eregi($keyword_allowed[$i], $_GET["isms_restemsg"]))
second argument is passed as null in eregi function
eregi is deprecated stop using it replace with preg_match
I'm not quite sure yet, but there are probably other ways to achieve what you are trying to do.
First you could use a more specific regular expression to get rid of the loop. This checks for two alternatives, STOP and the empty string (this is probably what failed with your eregi test).
if (preg_match('/^(STOP | )$/ix', $_GET["isms_restemsg"], $r))
{
$found_keyword = "Y";
$keyword_cf = $r[0];
}
else {
$found_keyword = "Y";
}
Or since you only need to check against two values:
if (in_array(strtoupper($_GET["isms_restemsg"]), array("STOP", "")) {
$found_keyword = "Y";
}
Related
I have 3 variables :
$a = 5;
$b = 3
$o = "*";
The $o variable contains a string value. This value can also be "/", "+", "-".
So when I concatenate $a.$o.$b :
$result = $a.$o.$b;
echo $result;
The result is 5*3 (a string) instead of 15.
So how to convert operator string into real operator ?
You can't, you'd need to make a function or a switch statement to check each of the operators.
Read this question and its answers so you'll understand how to do it.
Actually you can do it, by using eval. But it hurts to recommend using eval, so I just give you a link to another question with a good answer: calculate math expression from a string using eval
You can use eval. For example:
eval('echo 5*3;')
will echo the number 15.
Simple, short and save solution:
$a = 5;
$b = 3
$o = "*";
$simplecalc = function($a,$b,$op) {
switch($op):
case "*":
return $a*$b;
case "+":
return $a+$b;
case "-":
return $a-$b;
case "/";
return $a/$b;
default:
return false;
endswitch;
};
$result = $simplecalc($a,$b,$o);
I believe this is what you are looking for.
$a = 5;
$b = 3;
$o = "*";
$result = eval( "echo $a$o$b;" );
echo $result;
Please note that using eval() is very dangerous, because it allows execution of arbitrary PHP code.
I am a beginner in PHP and I am trying to separate the input based on the argument. Following is my code but it seems that my $arg variables is never set. Can someone point out my error?
$sender = $_GET['sender'];
$receiver = $_GET['receiver'];
$message = $_GET['message'];
$temp = explode( '.', $message);
$tempcnt = count($temp);
echo $temp[$tempcnt - 1];
if($tempcnt > 2)
{
if($temp[$tempcnt-1] === 'mp4')
{$arg = 3;}
elseif($temp[$tempcnt-1]==='jpg')
{$arg = 2;}
else
{$arg = 1;}
}
echo "Value of arg is" . $arg;
I have even tried with == and === and strcmp in if but still same issue.
Try This:
<?php
$temp strrchr("foo.jpg",".");
if($temp==".mp4")
$arg = 3;
elseif($temp==".jpg")
$arg = 2;
else $arg = 1;
?>
See also the other answers, but one possibility that hasn't been mentioned is that == and === and strcmp all compare case sensitively. So they won't find extensions like .MP4.
The solution in that case would be to use strcasecmp.
However, the first thing to do with problems like this is to output some more diagnostics, so that you can see for yourself what goes wrong. In this example, echo $tempcnt; after its assignment, or else echo "did nothing" after the outer if {..} block.
That way you'll be able to follow what the program flow is.
Issue was caused since i didn't realize i had compared for args > 2. Made it >=2 and viola it done!!
Thanks to #barmar for pointing that out!
I have a really quick question for you:
I read data from an Excel sheet and want to transform it into an assoc array. But sometimes there are no values given in some cells. So if this occurs I want to set the value of the array to 0.
right now I do it like that with the ternary operator and I'm glad I discovered that today:
(isset($excel->sheet[0]['cells'][$row][$value]) ? $excel->sheet[0]['cells'][$row][$value] : 0)
Is there a whay to shorten the repitition in this case? It works but it ain't that pretty :(
Although this is not recommended, I would go the following way (PHP 5.3):
(#$excel->sheet[0]['cells'][$row][$value] ? : 0);
Error suppression operator is a mess, but in this case the only thing you suppress is a well-known notice about undefined variable.
Another option (as stated by Álvaro G. Vicario) could be a simple cast to int (as NULL casts to 0):
(int)#$excel->sheet[0]['cells'][$row][$value];
Another option is making a function to check the existence of such variable – maybe it's a little over-engineering, overkill or just too much –:
function iset($array, $output) {
$args = func_get_args();
$val = $array;
for ($i = 1; $i < count($args) - 1; $i++) {
if (!isset($val[func_get_arg($i)])) {
return func_get_arg(func_num_args() - 1);
}
$val = $val[func_get_arg($i)];
}
return $val;
}
Then use the function like this:
$var = iset($excel->sheet, 0, 'cells', $row, $value, "DEFAULT_VALUE");
I am doing this check on a variable:
if (empty($num) || !isset ($num) || !is_numeric ($num))
{
$population = -1;
}
else
{
$population = $num;
}
And what I was hoping for is that if num is null or not a number or doesn't exist, to make $population = -1 and in all other cases to give $population the value of $num
But that is not happening for me. Any ideas why this isn't working the way I thought it would?
Is this possibly an issue with scoping?
<?php
$num=23;
tryStuff();
function tryStuff(){
global $num; //if this line is commented out, then -1 is printed.
if (empty($num) || !isset ($num) || !is_numeric ($num))
{
$population = -1;
}
else
{
$population = $num;
}
echo "$population<br>";
}
?>
is_numeric should work good by itself. If instead of $num the value was a super global, using isset would be a good idea to avoid warnings:
$population = is_numeric ($num) ? $num : -1;
// or
$population = isset($_GET['num']) && is_numeric($_GET['num']) ? $num : -1;
post an example of $num
using regex:
$population = preg_match("/^\d+$/", $num) ? $num : -1;
I'm going to go out on a limb here and say that you're inputting the number 0 and getting unexpected results, because empty(0) is true.
I think if you change your code to:
if (!isset ($num) || !is_numeric ($num))
{
$population = -1;
}
else
{
$population = $num;
}
You will get the desired results.
EDIT Possibly you are looking for an Integer or a Float in which case you should replace is_numeric with is_int or is_float respectively.
Why not flip it around and go with a positive as a primary check?
$population = (isset($num) && is_numeric($num)) ? $num : -1;
I've never had fun with negative's and "or" statements :)
What happens if you var_dump($num);?
Personally, my guess is that PHP is interpreting something input as a number, when you are expecting it to be a string. Such examples might include things which might accidentally convert, like '0xFF' (a string of the Hex for 255).
Clearly the issue is not about isset, because if it were, you would have caught it, and you said to evolve that this happens even without empty. This means that something which you are expecting to be is_numeric($num) === FALSE can be evaluated as TRUE.
The standard PHP way to test whether a string $str ends with a substring $test is:
$endsWith = substr( $str, -strlen( $test ) ) == $test
Is this the fastest way?
What Assaf said is correct. There is a built in function in PHP to do exactly that.
substr_compare($str, $test, strlen($str)-strlen($test), strlen($test)) === 0;
If $test is longer than $str PHP will give a warning, so you need to check for that first.
function endswith($string, $test) {
$strlen = strlen($string);
$testlen = strlen($test);
if ($testlen > $strlen) return false;
return substr_compare($string, $test, $strlen - $testlen, $testlen) === 0;
}
This method is a tiny bit more memory-expensive, but it is faster:
stripos(strrev($haystack), $reversed_needle) === 0;
This is best when you know exactly what the needle is, so you can hard-code it reversed. If you reverse the needle programmatically, it becomes slower than the earlier method.
Edit (12 years later): LOL, this is a super-old answer that I wrote when I didn't know what I was actually talking about. I'd like the think I've grown since then. #DavidHarkness is right, it is not very efficient in the negative case. Probably much faster to just iterate in reverse and bail early if you really need as much perf as possible. Also, php probably has better ways to do this now. Honestly, I haven't written php in nearly a decade, so I'll leave it up to others now.
$endsWith = substr_compare( $str, $test, -strlen( $test ) ) === 0
Negative offset "starts counting from the end of the string".
Here’s a simple way to check whether one string ends with another, by giving strpos an offset right where the string should be found:
function stringEndsWith($whole, $end)
{
return (strpos($whole, $end, strlen($whole) - strlen($end)) !== false);
}
Straightforward, and I think this’ll work in PHP 4.
It depends on which sort of efficiency you care about.
Your version uses more memory due to the extra copy from the use of substr.
An alternative version might search the original string for the last occurrence of the substring without making a copy, but would probably be slower due to more testing.
Probably the most efficient way is to do loop char-by-char from the -sterlen(test) position till the end of the string and compare. That's the minimal amount of comparisons you can hope to do and there's hardly any extra memory used.
In PHP 8:
str_ends_with('haystack', 'stack'); // true
str_ends_with('haystack', 'K'); // false
and also:
str_starts_with('haystack', 'hay'); // true
PHP RFC: Add str_starts_with(), str_ends_with() and related functions
Another way would be to use the strrpos function:
strrpos($str, $test) == strlen($str) - strlen($test)
But that’s not faster.
I hope that the below answer may be efficient and also simple:
$content = "The main string to search";
$search = "search";
//For compare the begining string with case insensitive.
if(stripos($content, $search) === 0) echo 'Yes';
else echo 'No';
//For compare the begining string with case sensitive.
if(strpos($content, $search) === 0) echo 'Yes';
else echo 'No';
//For compare the ending string with case insensitive.
if(stripos(strrev($content), strrev($search)) === 0) echo 'Yes';
else echo 'No';
//For compare the ending string with case sensitive.
if(strpos(strrev($content), strrev($search)) === 0) echo 'Yes';
else echo 'No';
Don't know if this is fast or not but for a single character test, these work, too:
(array_pop(str_split($string)) === $test) ? true : false;
($string[strlen($string)-1] === $test) ? true : false;
(strrev($string)[0] === $test) ? true : false;
easiest way to check it via regular expression
for example to check if the mail given is gmail:
echo (preg_match("/#gmail\.com$/","example-email#gmail.com"))?'true':'false';
I'm thinking the reverse functions like strrchr() would help you match the end of the string the fastest.
This is pure PHP, without calling external functions, except for strlen.
function endsWith ($ends, $string)
{
$strLength = strlen ($string);
$endsLength = strlen ($ends);
for ($i = 0; $i < $endsLength; $i++)
{
if ($string [$strLength - $i - 1] !== $ends [$i])
return false;
}
return true;
}
for single-char needle:
if (#strrev($haystack)[0] == $needle) {
// yes, it ends...
}