Regex Pattern返回一个空数组

时间:2013-01-25 00:12:34

标签: php wordpress preg-match jwplayer preg-match-all

我想要完成的是一个相当简单的正则表达式模式,最终会刮掉页面/自定义帖子类型的内容。暂时我只是检查一个单行字符串。

以下RegEx模式有效(复制并粘贴到RegExr - http://regexr.com)。

$pattern = "/\[jwplayer(.+?)?\]?]/g"; 
$videoTest = "[jwplayer config=\"top_10_videos\" mediaid=\"107\"]";
preg_match($videoTest, $pattern, $matches);
print_r($matches);`

但输出如下:

Array
(
    [0] => Array
        (
        )
)

我已经测试了其他正则表达式模式(简单的)并且我已经搜索了网络(包括堆栈溢出)以获得对此特定问题的答案,但尚未成功解决该问题。上面的php代码已放在WordPress v 3.5的functions.php中,如果该信息有用并且使用'wp_ajax'挂钩调用。 ajax钩子按预期工作。

任何人都可以提供任何帮助都很棒!

谢谢, 尼克

1 个答案:

答案 0 :(得分:3)

g修饰符为not used in PHP。请改用preg_match_all()

此外,preg_match的参数顺序错误。参数必须按此顺序排列:

preg_match($pattern, $videoTest, $matches);

阅读Regular Expressions documentation

使用正则表达式从字符串中检索内容的更健壮的方法尽可能具体。这可以防止畸形的东西通过。例如:

function getJQPlayer($string) {
    $pattern = '/\[jwplayer(?:\s+[\w\d]+=(["\'])[\w\d]+\\1)*\]/';
    preg_match_all($pattern, $string, $matches, PREG_SET_ORDER);
    foreach ($matches as & $match) {
        $match = array_shift($match);
    }
    return $matches ?: FALSE;
}
$videoTest  = "[jwplayer config=\"top_10_videos\" mediaid=\"107\"]";
$videoTest .= ",[jwplayer config=\"bottom_10_videos\" mediaid=\"108\"]";
echo '<pre>', print_r(getJQPlayer($videoTest), true);