【问题标题】:Regex keeps returning null正则表达式不断返回 null
【发布时间】:2018-04-25 09:48:06
【问题描述】:

我正在尝试使用正则表达式解析字符串。我得到的结果是一个没有内容的多维数组。它返回正确数量的子数组,但没有结果。下面是传入的 PHP 结果、正则表达式代码和字符串。有人能说明为什么结果为空吗?这是一个示例,表明它不起作用http://sandbox.onlinephpfunctions.com/code/d9dead4e23b5784a9a5ba7a098a958edb7113f62

我得到的结果

Array ( [0] => Array ( ) [1] => Array ( ) )

正则表达式代码

$content = $fetcher->fetchFile($directory.'/'.$fileName);
        preg_match_all('/\[@style\](.*?)\[@end\]/s', $content, $matches);
        print_r($matches);

正在解析的字符串

ul.nav > li > a {
  padding: 0 10px; }
/**
 *  @style
 */
button {
  background: blue !important; }
/*  @end */
/**
 *  @style
 */
span {
  background: blue !important;
  display: block;
  height: 20px;
  width: 20px; }
/* @end */

【问题讨论】:

  • 您的正则表达式在@style@end 周围有[],删除它们。见regex101.com/r/wxPQex/1
  • 当你可以捕获所有样式时为什么要使用标签,/([-0-9a-zA-Z,.:\[\]()\s#>]+\{[^}]+\})/Test it!
  • 我不想只捕捉样式,我也想捕捉 cmets
  • 删除 [] 也确实有效
  • 这里有一个例子表明它不起作用sandbox.onlinephpfunctions.com/code/…

标签: php regex


【解决方案1】:

您可以尝试使用:

preg_match_all("/\/\*\*\s*\*\s*\@style\s*\*\/(.*?)\/\*\s*\@end\s*\*\//s", $input, $matches, PREG_PATTERN_ORDER);
print_r($matches[0]);

这将输出:

Array
(
    [0] => /**
 *  @style
 */
button {
  background: blue !important; }
/*  @end */
    [1] => /**
 *  @style
 */
span {
  background: blue !important;
  display: block;
  height: 20px;
  width: 20px; }
/* @end */
)

【讨论】:

  • 谢谢,但是需要返回css周围的cmets
猜你喜欢
  • 1970-01-01
  • 2013-06-02
  • 2017-11-22
  • 1970-01-01
  • 2020-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-29
相关资源
最近更新 更多