<code>在做一个php中文验证码时,按原本的思路是将一段文字分割成一个个文字组成个文字数组,然后遍历四次,随机生成四个验证文字,然后画在image上,可是发现用`str_split($str,3)`来分割有时会少一个文字,换成`explode(" ",$str)`还是偶尔缺字。。。主要代码如下:` $fontFace='aa.ttf'; $str=" 大 闸 是 中 国 主 导 品 牌 亦 行 业 协 会 重 点 推 荐 家 集 养 殖 与 销 售"; $strDb=str_split($str,3);for($i=0;$i<4;$i++){ $fontColor=imagecolorallocate($img,mt_rand(0,120),mt_rand(0,120),mt_rand(0,120)); $index=mt_rand(0,count($strDb)+1); $cn=$strDb[$index]; $captcha.=$cn; $x=($i*120/4)+mt_rand(5,10); $y=mt_rand(25,45); imagettftext($img,15,mt_rand(-30,60),$x,$y,$fontColor,$fontFace,$cn);}`感觉是文字编码的问题,字节数设为4的时候也可以显示部分文字,可是具体怎么解决不知道,求帮助,谢谢!</code>
回复内容:
本文来源[email protected]搞@^&代*@码)网9搞代gaodaima码
<code>在做一个php中文验证码时,按原本的思路是将一段文字分割成一个个文字组成个文字数组,然后遍历四次,随机生成四个验证文字,然后画在image上,可是发现用`str_split($str,3)`来分割有时会少一个文字,换成`explode(" ",$str)`还是偶尔缺字。。。主要代码如下:` $fontFace='aa.ttf'; $str=" 大 闸 是 中 国 主 导 品 牌 亦 行 业 协 会 重 点 推 荐 家 集 养 殖 与 销 售"; $strDb=str_split($str,3);for($i=0;$i<4;$i++){ $fontColor=imagecolorallocate($img,mt_rand(0,120),mt_rand(0,120),mt_rand(0,120)); $index=mt_rand(0,count($strDb)+1); $cn=$strDb[$index]; $captcha.=$cn; $x=($i*120/4)+mt_rand(5,10); $y=mt_rand(25,45); imagettftext($img,15,mt_rand(-30,60),$x,$y,$fontColor,$fontFace,$cn);}`感觉是文字编码的问题,字节数设为4的时候也可以显示部分文字,可是具体怎么解决不知道,求帮助,谢谢!</code>
<body>
两个点,第一个是$str不用空格分开,第二个是生成随机index的时候,应该是-1,不是+1
像这种取数组中某个随机值的时候,index可以用array_rand()
函数来生成
改完如下
<code>$fontFace='aa.ttf'; $str="大闸是中国主导品牌亦行业协会重点推荐家集养殖与销售"; $strDb=str_split($str,3);for($i=0;$i<4;$i++){ $fontColor=imagecolorallocate($img,mt_rand(0,120),mt_rand(0,120),mt_rand(0,120)); $index=array_rand($strDb); $cn=$strDb[$index]; $captcha.=$cn; $x=($i*120/4)+mt_rand(5,10); $y=mt_rand(25,45); imagettftext($img,15,mt_rand(-30,60),$x,$y,$fontColor,$fontFace,$cn);}</code>
用mb扩展的函数处理字符串,解决编码问题,另外空格有啥用么?
如果$str含中英文用这个分割$strDb=preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);