while loop in the PHP code excecuting infinite times - php

<?php
$string="I am Azizul hakim.I am a student.I am feeling good today";
$find="am";
$i=0;
$find_length=strlen($find);
while($i<strlen($string))
{
$pos=strpos($string,$find,$i);
echo $pos;
$i=$pos+$find_length;
}
?>
The php code is executing infinite times.Although the limit is restricted by specifying the string length of the string.Why it is executing infinite times?

strpos returns false, which evaluates to 0, when your remaining $string doesn't contain $find and the loop starts over again.

In cases like this, I believe perl compatible regular expression, (pcre), is always the best choice. Why, because you will use only (1) function / method call, and then simple loop to process the result. With string type functions / methods, each time your $needle is found in your $haystack you will need to call another string type function / method to handle the next occurrence of your $needle being found in your $haystack!

Related

Can someone explain to me why this PHP code works?

I've found this piece of nifty PHP code somewhere online:
<?=($__='`#`#'^'*/).')(($_='->.<:'^'__#[_')('>'^#_,'%'^#_)),$__($_('|'^'=','|'^'&')),$__($_(':'^"\n",';'^']'^#_));
When you run it, it produces the following string of text:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
Why does this work the way it does?
What you start out with is <?=(value),(value),(value); so you can rewrite it like this.
echo ($__='`#`#'^'*/).')(($_='->.<:'^'__#[_')('>'^#_,'%'^#_));
echo $__($_('|'^'=','|'^'&'));
echo $__($_(':'^"\n",';'^']'^#_));
Line 1:
$__ = '`#`#'^'*/).' uses ^, which is the bitwise operator to shift `#`# by */). and set $__ to the string 'JoIn', next it does this to $_, setting it to the string 'range'.
$__() and $_() are now aliases of join() and range().
Making the first line easier to read:
echo ($__='join')(($_='range')('>'^#_,'%'^#_));
Wrapping pieces in parenthesis serves to set the var and then pass its value as an expression so you can do fancy things like this.
A little cleaner:
$__ = 'join';
$_ = 'range';
echo $__($_('>'^#_, '%'^#_));
The two args for the inner function: '>'^#_ and '%'^#_, are 'a' and 'z'. (These abuse the error suppression operator # to kill a warning and use _ as a string, so '>'^'_' and '%'^'_')
Now you have echo join(range('a', 'z')); giving you abcdefghijklmnopqrstuvwxyz.
Second line passes '|'^'=' and '|'^'&' or A and Z to those two functions.
And the third line passes 0 and 9.
The biggest takeaway from this is that you should never use any of these tricks in production code.

Evaluate mathematical operations inside a string using PHP

I want to evaluate a mathematical operations inside the string after I get it in that string.
Here is the string
$string = "Add this two numbers [4+2+2]. And [5*3/2] will result to?"
I already get those numbers:
$f_number = "4+2+2";
$s_number = "5*3/2";
How can I evaluate this automatically using any function?
Sample:
echo anyfunction($f_number);//will result to 8
echo anyfunction($s_number);//will result to 7.5
because if I will echo directly it will just output like this:
echo $f_number;//will result to 4+2+2
echo a$s_number;//will result to 5*3/2
You can use eval. It's probably the easiest way out. Mind though that it can also be used for other expressions, because it basically executes any PHP code that is in the string.
But by wrapping it in a function, like you intended, you can at least black box it, and add safety measures later if you need to, or even switch to a different expression evaluator, without having to change all your code.
A simple safety measure would be to check if the string only contains numeric values, whitespace and allowed operators. That way it should be impossible to secretly inject actual code.
function anyfunction($expr)
{
// Optional: check if $expr contains only numerics and operators
// actual evaluation. The code in $expre should contain a return
// statement if you want it to return something.
return eval("return $expr;");
}
echo anyfunction($f_number);

How to convert string variable to integer in php?

I'm very new to php .I want to convert the string to integer value.
I used following code to convert
$val='(100*2)';
echo (int)($val); //This will showing output as 0
But echo (int)((100*2)); /This will showing output as 200
Please help me any one to solve this .Thanks advance
(int)($val) evaluates to 0 because $val's value is not a numeric string (ie one that can be directly cast to a number).
If you really need this kind of functionality, try eval():
$val='(100*2)';
echo (int)($val); //This will showing output as 0
eval('$newval='.$val.';');
echo $newval;
But be warned: eval() can be dangerous!
From http://php.net/manual/en/function.eval.php:
Caution
The eval() language construct is very dangerous because it allows
execution of arbitrary PHP code. Its use thus is discouraged. If you
have carefully verified that there is no other option than to use this
construct, pay special attention not to pass any user provided data
into it without properly validating it beforehand.
EDIT: Added .';' to eval parameter to make it a legit php instruction.
The most common suggestion will be - evaluate your string as PHP code, like:
$val = '(100*2)';
eval('$val = '.$val.';');
-but that's unsafe, eval should be avoided as long as possible.
Alternatively, there is bcParser for PHP, which can solve such issues. That's more safe than eval.
Finally, I doubt that you really need do such things - it seems you're solving some problem with wrong method (see XY-problem description)
You can do it using php eval function.
For that first you have to check for special characters and equation characters.
$val='(100*2)';
echo matheval($val);
function matheval($equation)
{
$equation = preg_replace("/[^0-9+\-.*\/()%]/","",$equation);
// fix percentage calcul when percentage value < 10
$equation = preg_replace("/([+-])([0-9]{1})(%)/","*(1\$1.0\$2)",$equation);
// calc percentage
$equation = preg_replace("/([+-])([0-9]+)(%)/","*(1\$1.\$2)",$equation);
// you could use str_replace on this next line
// if you really, really want to fine-tune this equation
$equation = preg_replace("/([0-9]+)(%)/",".\$1",$equation);
if ( $equation == "" )
{
$return = 0;
}
else
{
eval("\$return=" . $equation . ";" );
}
return $return;
}
I not recommended this, but you can use eval to suit your need
eval('$val = (100*2)');
echo intval($val);
Why not just:
$x=intval(100);// <- or an other value from the cleaned user input
$y=intval(2);
$val=$x*$y;
echo $val;
You are not giving a goal.
I can just explain why your code works like it does.
'(100*2)' is a String that cannot be converted to int, since it does contain other chars than numbers. Every String that cannot be converted will result in 0.
echo (int)(100*2) will work, because you use numbers and no strings. No need to convert, either, would work without the cast, just echo (100*2);
Remember PHP use loose typing. You will almost never need to convert types. This scenario is very set up.

how to warn user if it is used a strange character in eval operation

$op=$_POST['param'];
$statement=eval("return ($op);");
in 'param', if there is a strange character such letter 'jfsdf' or something else the eval function does not work. How can I solve this problem?
eval function works only well defined entries such as '54+4*3' on the other hand if it is used entries such '6p+87+4' it gives an parse error. Is there any way to warn user in order to enter a well defined statement
First of all, depending on what you mean by "strange" character, you should implement function that verifies the string coming from outside.
$allowed_chars = array('function', 'this' ); //..add desirable ones
function is_alloved_char($char){
return in_array($char, $allowed_chars);
}
RegEx is great for this when You Do except some performance down.
In your situation str_pos() is great enough to match undesirable chars.
so, your another function should be similar to:
/**
*
* #param string
* #return TRUE on success, FALSE otherwise
*/
function is_really_safe($char){
global $allowed_chars; //just make this array visible here
foreach ($allowed_chars as $allowed_char){
if ( str_pos($allowed_char, $char) ){
return false;
}
}
return true;
}
Also, be VERY VERY careful with eval()
If you use this function in product, then you are doing something wrong.
If it's about evaluation a constrained math expression, then the lazy option would be to use a pattern assertion prior evaluating. This one's also easier as it returns you the expression result implicitly:
$result = preg_replace('#^\s*\d+([-+*/%]\s*\d+\s*)*$#e', '$0', $input);
Would need something more complex if you wanted to assert (..) parens are correctly structured as well.
If it doesn't match, it will return the original input string. Check that for generating a warning.

Searching partial strings PHP

How can you search a partial string when typing (not to use MySQL) like the LIKE function in MySQL but using PHP when searching a string, e.g.
<?php
$string = "Stackoverflow";
$find = "overfl";
if($find == $string)
{
return true;
}
else
{
return false
}
?>
But that will obviously work won't, but is there a function where you can search partially of a string? That would be great :)
EDIT:
What if it was in an array?
if i use the strpos, it does the echo, If I use it, it goes like truetruetruetruetrue.
I tend to use strpos
$needle='appy';
$haystack='I\'m feeling flappy, and you?';
if(strpos($haystack,$needle)!==false){
//then it was found
}
If you want it to ignore case, use stripos.
Note that a subtlety about this is that if the needle is at the very start of the haystack, in position 0, integer 0 is returned. This means you must compare to false, using strict comparison, or it can produce a false negative.
As noted in the manual, linked above
Warning
This function may return Boolean
FALSE, but may also return a
non-Boolean value which evaluates to
FALSE, such as 0 or "". Please read
the section on Booleans for more
information. Use the === operator for
testing the return value of this
function.
As far as using arrays, strpos is meant to take two strings. Using an array will produce Warning: strpos() expects parameter 1 to be string, array given or 1Warning: strpos(): needle is not a string or an integer`.
Okay, let's say you have an array of strings for which to search.
You can
$needles=array('hose','fribb','pancake');
$haystack='Where are those pancakes??';
foreach($needles as $ndl){
if(strpos($haystack,$ndl)!==false){ echo "'$ndl': found<br>\n"; }
else{ echo "'$ndl' : not found<br>\n"; }
}
Another way of searching for multiple strings in one string, without using an array... This only tells you whether at least one match was found.
$haystack='Where are those pancakes??';
$match=preg_match('#(hose|fribb|pancake)#',$haystack);
//$match is now int(1)
Or, use preg_match_all to see how many matches there are, total.
$all_matches=preg_match_all('#(hose|fribb|pancake)#',$haystack,$results);
//all_matches is int(2). Note you also have $results, which stores which needles matched.
In that, the search term is a regular expression. () groups the terms together, and | means 'or'. # denotes the beginning and end of the pattern. Regexes can get pretty complicated quickly, but of course, they work! They are often avoided for performance reasons, but if you're testing multiple strings, this might be more efficient than they array looping method described above. I'm sure there are also other ways to do this.
strstr() / stristr() (the latter being case-insensitive)
if(strstr($string,$find)!==false){
//true
}
strpos() can do that.
if(strpos($string, $find) !== false)
. . .
Note that it may return 0, so do use the type-equals operator.

Categories