我是愚蠢还是preg_match()
不接受全局类变量?
class test{
private$username,$usernameValidation;
public function __construct($username){
$this->username=$username;
$this->usernameValidation="/^[a-zA-Z0-9]{0,8}$/";
}
public function validate(){
if(!preg_match($this->usernameValidation,$this->username)){
//failed;
}
}
}
每次我编译这样的函数时,它似乎告诉我表达式是空的。
似乎工作为preg_match("/^[a-zA-Z0-9]{0,8}$/",$this->username);
。
答案 0 :(得分:1)
{,8}
不是有效的重复,我想你想要:{0,8}
或{8,}
答案 1 :(得分:1)
您可以尝试在课程级别保留正则表达式分配:
class test {
const UsernameValidation = '/^[a-zA-Z0-9]{0,8}$/';
private $username;
public function __construct($username){
$this->username=$username;
}
public function validate(){
if(!preg_match(UsernameValidation, $this->username)) {
//failed;
}
}
}
答案 2 :(得分:0)
您需要private
和$username
之间的空格,否则您将收到语法错误。此代码有效:
class test{
private $username,$usernameValidation;
public function __construct($username){
$this->username=$username;
$this->usernameValidation="/^[a-zA-Z0-9]{0,8}$/";
}
public function validate(){
if(!preg_match($this->usernameValidation,$this->username)){
echo 'failed';
}
else {
echo 'matched';
}
}
}
$foo = new test('abcdefg');
$foo->validate();