PHP strpos to find the value of type integer Abnormal Analysis and Solutions

Recent operational colleagues to reflect, many users publish posts content into a pending state

Since we have a system of checking mechanisms sensitive words, if the message contains sensitive words into the hair after the first trial

Which it uses strpos function is well known, strpos to find the location of a string of the first occurrence of the substring.

Every time data, and want to find a character in the string is present, it will be used to it.

But the investigation found that in some posts we practice does not exist keyword set, then this is because of what?

Investigation found that some operators set purely digital Keywords

analysis

Suppose there is a string of "I do not happy! Xxxx585xxx", now we need to find the location of 585 appears, check whether there is the keyword.

Ideally, we might think that the code can describe this, of course, most of the time may indeed be written like this

$string ='I don\'t happy ! xxxx585xxx';
$numtmp = 585;
echo strpos($string,$numtmp);   

But we unexpectedly appeared in examination results in an error, its output is zero, but our expectations are 20

This time there have been a result of an error, while when the check 585 is 0, the content will determine the existence of this string, but it will be 5 to check if it is false.

the reason

That spirit of seeking the true spirit, because in the end what is it? Concluded after the reference partial information

strpos the data using a non-string type php_needle_charmade a cast, the cast.

C code, if it is an integer type, then cast into char type. So when you pass 585, the resulting char after use for a strong turn string "I", so in fact taken after the string length is zero.

Now it is clear, because the bottom of the PHP numerical parameters made a mandatory conversion, so that the content of her own to check changes, it appears the result of an error

 Note that type conversion is divided into the following situations:

 1, shaping, is directly converted to a long integer type char

 2, Boolean, were transfected into the character '1', '0', so strpost ( 'e1', true); return 1 content

 3, double data type, the first strong into a long integer converted to char type

 4, the target object id for char conversion

 5, warn other types of trigger E_WARNING here to understand why the result to an integer, strpos will be less than the intention.

 solution

Since the system needs to character data, that we are to be examined in advance of the data  (string) process Jieke

//方案1
$string ='I don\'t happy ! xxxx585xxx';
$numtmp = '585';
echo strpos($string, $numtmp);

//方案2
$string ='I don\'t happy ! xxxx585xxx';
$numtmp = 585;
echo strpos($string, (string)$numtmp);

In this way we get the expected results -

 

Author: An old <[email protected]> way to solve the problem is to solve it once

Guess you like

Origin www.cnblogs.com/widgetbox/p/12095541.html