【问题标题】:Regex - get class property value正则表达式 - 获取类属性值
【发布时间】:2014-07-02 10:00:11
【问题描述】:

我有这样的字符串:

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] 是'获取这个值';

【问题讨论】:

  • 你为什么要捕获你所有的.*s?

标签: php regex


【解决方案1】:

虽然我确信有更好的方法来实现您想要的,但这里有一个应该匹配 $db 的值的正则表达式:

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

查看使用中here。

【讨论】:

  • 具体来说,问题在于未转义的$。
  • @NiettheDarkAbsol 不仅如此,\'(.*)\' 匹配的比 OP 想要的多,我让它变得不贪心。
  • preg_match('/public\s+\$db\s+=\s+\'(.*?)\';/i',$file,$matches); 空数组
【解决方案2】:

你可以这样做,

<?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"
  }
}

【讨论】:

  • 您需要像我在示例中所做的那样转义输入中的$ 符号。
  • 我不能。字符串是动态的,我无法更改任何内容
  • @turson 现在您不需要在输入中转义 $。
猜你喜欢
  • 2012-11-26
  • 1970-01-01
  • 2011-07-28
  • 1970-01-01
  • 2011-02-01
  • 2012-06-12
  • 1970-01-01
  • 2023-03-06
  • 2014-03-01
相关资源
最近更新 更多