正则表达式 - 获取类属性值

时间:2014-07-02 10:00:11

标签: php regex

我的字符串如下:

public $host = 'sth'; public $user = 'sth'; public $password = 'sth';public $db = 'dbname';        public $dbprefix = 'sth';

我想动态获取$ db值。我试过正则表达式:

#(.*)public(.*)$db(.*)=(.*)\'(.*)\';#is

空数组结果

请不要写我可以获得课堂和财产的实例,因为我不能,而且这就是全部。除了正则表达式之外,还有更多的东西。

问题解决了!

$file="public $host = 'sth';        public $user = 'sth';        public $password = 'sth';        public $db = 'get this value';
        public $dbprefix = 'sth';";
$regex = "/.*public\s+$db\s+=\s+'(.*?)';/i";
preg_match($regex,$file,$matches);
echo '<br><pre>';var_dump($matches);

$ matches [1]是'得到这个值';

2 个答案:

答案 0 :(得分:0)

虽然我确信有更好的方法可以达到你想要的效果,但这里的正则表达式应与$db的值相匹配:

/public\s+\$db\s*=\s*'(.*?)';/i

在使用中查看here

答案 1 :(得分:0)

你可以这样做,

<?php
$mystring = <<<'EOD'
public $host = 'sth'; public $user = 'sth'; public $password = 'sth';public $db = 'dbname';        public $dbprefix = 'sth';";
EOD;
$regex = '~(?<=public \$db = \')[^\']*~';
preg_match_all($regex, $mystring, $matches);
var_dump($matches);
?>

输出:

array(1) {
  [0]=>
  array(1) {
    [0]=>
    string(6) "dbname"
  }
}
相关问题