代码如下:
<code><span>/** *<span> @param</span> $string *<span> @param</span> $from 从0开始…… *<span> @param</span> null $length *<span> @return</span> string * c_substr("给我一点", $from=0, 9)>>给我一 * c_substr("给我一点", $from=1, 9)>>我一 * c_substr("给我一点", $from=2, 9)>>我一 * c_substr("给我一点", $from=3, 9)>>我一点 */</span><span>private</span><span><span>function</span><span>c_substr</span><span>(<span>$string</span>, <span>$from</span>=<span>0</span>, <span>$length</span> = null)</span>{</span><span>//必填字段校验</span><span>if</span>(!<span>isset</span>(<span>$string</span>)||!<span>isset</span>(<span>$from</span>)||<span>$from</span>0){ <span>return</span><span>''</span>; } <span>//获得字符串长度</span><span>$strLen</span> = strlen(<span>$string</span>); <span>//如果没有设置长度则把长度设置为字符串</span><span>if</span>(<span>$length</span> == <span>null</span>){ <span>$length</span> = <span>$strLen</span>; } <span>//判断字符串长度是否小于等于$length,是则直接返回字符串</span><span>if</span>(<span>$from</span> == <span>0</span>&&<span>$length</span> >= <span>$strLen</span>){ <span>return</span><span>$string</span>; } <span>$subLen</span> = <span>$length</span> + <span>$from</span>; <span>$rtnStr</span> = <span>""</span>; <span>//开始截取字符串</span><span>//为了能够截取完整,需要从头开始遍历</span><span>for</span>(<span>$i</span>=<span>0</span>;<span>$i</span>$subLen&&<span>$i</span>$strLen;<span>$i</span>++){ <span>//判断是否为中文 如果是则在不超长的情况下往后再截2个字节</span><span>if</span>(ord(<span>$string</span>[<span>$i</span>])><span>0xa0</span>){ <span>if</span>(<span>$i</span>+<span>2</span>$subLen&&<span>$i</span>+<span>2</span>$strLen){ <span>$rtnStr</span> .= <span>$string</span>[<span>$i</span>].<span>$string</span>[<span>$i</span>+<span>1</span>].<span>$string</span>[<span>$i</span>+<span>2</span>]; <span>/** * 如 “给我一点” * 从位置0截取9个字节,则只获取“给我一” * 从位置1截取9个字节,则只获取“我一” * 从位置2截取9个字节,则只获取“我一” * 从位置3截取9个字节,则只获取“我一点” * 下面的if是为了跳过开头不完整的字符 */</span><span>if</span>(<span>$i</span>$from){ <span>$rtnStr</span> = <span>""</span>; } <span>$i</span> += <span>2</span>; } <span>else</span>{ <span>return</span><span>$rtnStr</span>; } } <span>//英文</span><span>else</span>{ <span>$rtnStr</span> .= <span>$string</span>[<span>$i</span>]; } } <span>return</span><span>$rtnStr</span>; }</code>
版权声明:转载的时候提到我就行……
以上就介绍了PHP截取中英文,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。