douzhenyu6533 2012-05-28 16:14
浏览 26
已采纳

在PHP中自动连接OR正则表达式

I have a PHP array like so (comes from a MySQL database, YouTube is just an example):

[regexpr] => array(4) (
   [0] => (string) http://*.youtube.com/v/*
   [1] => (string) https://*.youtube.com/v/*
   [2] => (string) http://youtu.be/*
   [3] => (string) http://m.youtube.com/watch*
)

Now, what I am trying to achieve is to find any of the matches in a URL (in this case: checking if the URL is a valid YouTube URL).

What I have tried is the following:

for($i = 0; $i < count($regexpr); $i++)
   $regexpr[$i] = preg_quote($regexpr[$i]); // because of the URLs

$expr = '/(('. implode('|', $regexpr) . '))/i'; // Concatenating the ORs

$found = preg_match($expr, 'http://www.youtube.com/[foo]&v=MyVidID', $matches);

However, unfortunately, I was unable to successfully concatenate these expressions - I am not getting any successful "hits".

Would anyone have a pointer as to how to solve this issue?

¡Gracias!

  • 写回答

2条回答 默认 最新

  • dongluan6784 2012-05-28 16:19
    关注

    Problem is your source "regexs":

    http://*.youtube.com/v/*
           ^---            ^---
    

    the asterisks are "zero or more of the previous" character, not general wildcards. So you're causing the / chars to be made optional. What you want is probably .*, which is a "zero or more of ANY character"

    However, you're passing those through preg_quote, and that'll escape ANY regex metacharacters, so in effect you're not passing in ANY wildcards. You're passing in literal asterixes, literal periods, etc...

    You should escape the regexes yourself and skip the preg_quote stage, e.g.

    http:\/\/.*\.youtube.com\/v\/.*
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮