Home  >  Article  >  Backend Development  >  PHP中如何控制一个方法的字符串类型参数长度小于等于255字节?

PHP中如何控制一个方法的字符串类型参数长度小于等于255字节?

WBOY
WBOYOriginal
2016-06-06 20:10:421049browse

注意是字节哦

回复内容:

注意是字节哦

<code class="php">//直接报错
function test($str) {
    if (!is_string($str) or strlen($str) > 255) {
        throw new Exception('not a string or too long');
    }
}

//自动截断
function test2($str) {
    if (!is_string($str)) {
        throw new Exception('not a string');
    }
    $str = substr($str, 0, 255); //php的substr是二进制安全的
}</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn