【问题标题】:Undefined Offset / PHP error未定义的偏移量/PHP 错误
【发布时间】:2017-08-18 03:34:23
【问题描述】:

我正在使用包含此功能的 WordPress 插件,但插件开发人员的响应速度不是特别快。

它应该从 YouTube 网址获取视频 ID,但我却收到“未定义偏移量:1”错误。是否有我遗漏的编码错误?

函数如下:

function youtube_id_from_url($url) {
    $pattern =
        '%^# Match any youtube URL
        (?:https?://)?  # Optional scheme. Either http or https
        (?:www\.)?      # Optional www subdomain
        (?:             # Group host alternatives
          youtu\.be/    # Either youtu.be,
        | youtube\.com  # or youtube.com
          (?:           # Group path alternatives
            /embed/     # Either /embed/
          | /v/         # or /v/
          | /watch\?v=  # or /watch\?v=
          )             # End path alternatives.
        )               # End host alternatives.
        ([\w-]{10,12})  # Allow 10-12 for 11 char youtube id.
        $%x'
        ;
    $result = preg_match($pattern, $url, $matches);
    if (false !== $result) {
        return $matches[1];
    }
    return false;
}

我尝试执行print_r 来查看数组$matches 的样子,它似乎只是一个空数组,所以我尝试回显$result,它返回0,这意味着preg_match()找不到匹配项,对吗?如果是这样,我可以弄清楚$pattern 有什么问题会使其返回 0。

更新: 显然,还有一些其他功能正在获取 URL 并从中创建链接,然后将其保存为 $url 变量。如果我回显$url 变量,它将打印为<a href="youtube url">youtube url</a>.

这解释了错误,但我如何修改正则表达式以适应 html 标记?

【问题讨论】:

  • 你能添加导致错误的url吗?
  • preg_match 永远不会返回布尔值false(除非出现错误)。通常它会返回10。检查应该只是if ($result) {
  • 对我来说工作正常(除了@Phil 所说的):3v4l.org/eTvqp
  • 这个表达式不考虑额外的查询参数,例如&feature=youtu.be。尝试将最后一行更改为&?.*$%x'
  • 请显示 youtube 网址

标签: php wordpress preg-match


【解决方案1】:

preg_match 只会在发生错误时返回 FALSE,在这种情况下,您可能想知道是否有匹配项或没有匹配项。所以你应该可以换线了:

if (false !== $result) {

if ( isset( $matches[1] ) ) {

if ( $result && isset( $matches[1] ) ) {

正如 Phil 指出的,您真正需要的是:

if( $result ) {

Phil 对正则表达式的修改完成的完整修改函数:

function youtube_id_from_url($url) {
    $pattern =
        '%^# Match any youtube URL
        (?:https?://)?  # Optional scheme. Either http or https
        (?:www\.)?      # Optional www subdomain
        (?:             # Group host alternatives
          youtu\.be/    # Either youtu.be,
        | youtube\.com  # or youtube.com
          (?:           # Group path alternatives
            /embed/     # Either /embed/
          | /v/         # or /v/
          | /watch\?v=  # or /watch\?v=
          )             # End path alternatives.
        )               # End host alternatives.
        ([\w-]{10,12})  # Allow 10-12 for 11 char youtube id.
        &?.*$%x'
        ;
    $result = preg_match($pattern, $url, $matches);
    if ($result) {
        return $matches[1];
    }
    return false;
}

【讨论】:

  • $matches 将始终被设置(除非preg_match 返回false)。如果$result真实,则无需检查$matches
  • $matches 可能总是被设置,但 $matches[1] 会被设置吗?显然不是,否则他不会得到那个错误。
  • 如果模式匹配任何东西,$matches 将有两个元素,因为捕获组是非可选的
  • 这当然值得注意。我会修改我的答案。
  • 这只是返回为假,但请参阅我刚刚添加到原始问题的更新。
猜你喜欢
  • 2011-01-31
  • 1970-01-01
  • 1970-01-01
  • 2016-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多