PHP正则表达式很多匹配

问题描述 投票:2回答:2

我有一个Drupal config文件,其中包含这样的行集:

 *     'driver' => 'mysql',
 *     'database' => 'databasename',
 *     'username' => 'username',
 *     'password' => 'password',
 *     'host' => 'localhost',
 *     'prefix' => '',

(实际上是2次)并且它还有一组这样的行:

    array (
      'database' => 'dba',
      'username' => 'admin',
      'password' => 'admin1234',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

(在文件中仅发生一次)

如图所示,差异在于我需要定位/匹配的行上没有星号*(注释标签)。

我正在使用以下正则表达式,但它没有返回所需的字符串。

preg_match("#'password' => '(.*?)'#isU",$file_source , $pass);

这是我尝试的正则表达式模式演示:https://regex101.com/r/lDA4y4/2

我想要的是密码值:admin1234

php regex preg-match configuration-files
2个回答
1
投票

你可以使用正则表达式破解配置文件...

here is the demo为优化模式:/^ {6}'password' => '\K[^']*/m

但是,我担心你完全忽略了拥有.php配置文件的重点/美感。

如果您只需要include(或require)文件中需要它的脚本,那么您将可以直接和干净地访问它所拥有的所有变量和配置。这意味着:

include('config.php');  // you may need to modify the path for your case
$db=$databases['default']['default'];  // I recommend this line to simplify variable access

您将能够访问如下变量:

$db['database']; // = dba
$db['username']; // = admin
$db['password']; // = admin1234
$db['host']; // = localhost
$db['port']; // [empty string]
$db['driver']; // = mysql
$db['prefix']; // [empty string]

因此,您也将受益于其中的其他未注释的声明。

$update_free_access = FALSE;
$drupal_hash_salt = 'N5wfuEGIDhz8C8LuelMlQjkosDt2Avr9ygNciIbmAqw';
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 100);
ini_set('session.gc_maxlifetime', 200000);
ini_set('session.cookie_lifetime', 2000000);
$conf['404_fast_paths_exclude'] = '/\/(?:styles)|(?:system\/files)\//';
$conf['404_fast_paths'] = '/\.(?:txt|png|gif|jpe?g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i';
$conf['404_fast_html'] = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL "@path" was not found on this server.</p></body></html>';

如果您不想要任何其他声明,那么您可以将它们注释掉或手动创建一个仅包含所需声明的新配置文件(另外您可以简化$databases数组结构)。


2
投票

如果你只想要没有*的行,只需检查以空格开头的行:

preg_match("/^\s+'password'\s=>\s'(.+)',/im", $source, $matches);
$pass = $matches[1];

所以基本上用^\s+'password'你定义从^行开始直到字符串'password',它只能包含空格字符\s+(1或更多)。

见:https://regex101.com/r/KG4inA/2

© www.soinside.com 2019 - 2024. All rights reserved.