PHP substr() not working when 3rd parem is string like 0xe84?
I'm having problems using substr() with matches coming from a regular expression (using preg_match() - $a contains the array of matches).
When echo'ing a[1] it equals 0xe84 and is a string (as I've checked using gettype()).
substr($file, $a[2], $a[1]); //not working...
But if I do (Also note I can't actually do this as the third parem is generic coming from a regex - this is just used to illustrate my problem):
substr($file, $a[2], 0xe84); //works fine - when entering the match directly as an integer
So my question is why does substr() work only when the 3rd parem is of an integer type, and how can I make $a[1] an integer so it works fine?
I've tried doing type casting (using (int)), using intval() as well 开发者_运维问答as settype(integer) on $a[1], however $a[1] then becomes 0 (and the substr() won't work).
'0xe84' is a hex string, which is 3716 in decimal. You can convert it to an integer using hexdec:
substr($file, $a[2], hexdec($a[1]));
The reason it works when you pass 0xe84 without quotes is because php correctly interprets hex literals. However, it does not understand it as a hex number when used as a string '0xe84'.
For a safe code you can use the intval function to retrieve the integer value :
substr($file, $a[2], intval($a[1],16));
the second param of intval means the base, here we're using HEX
Regards NiL
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论