繁体   English   中英

正则表达式(preg_match_all)

[英]Regular Expression (preg_match_all)

我有一个私人网站,我在其中分享视频(和其他一些东西)。 我所实现的是,使用preg_match_all()可以自动找到链接,并将带有HTML代码的视频粘贴到我的网站。

这里是一个例子:

    <?php
$matchwith = "http://videosite.com/id1 http://videosite.com/id2 http://videosite.com/id3";
preg_match_all('/videosite\.com\/(\w+)/i', $matchwith, $matches);  
foreach($matches[1] as $value)
{  
  print '<a href="http://videosite.com/'.$value.'">Hyperlink</a>';           
}      
    ?>

这可行。 我知道这样做可能会更容易,但是必须采用这种方式。

但是我不知道这是一部分为两部分的电影。 这里是一个例子:

    $matchWith = "http://videosite.com/id1_movie1 http://videosite.com/id2_movie1"
               "http://videosite.com/id3_movie2 http://videosite.com/id4_movie2";

http://videosite.com/ (...)之后的所有内容都是唯一的。

我想要的是,如果您在链接之前编写第1部分和第2部分(或其他内容),它会自动将其检测为该视频的第1部分和第2部分。

$ matchwith可能包含其他电影。

所以我相信这是您需要的:

<?php
$matchWith = "Movie 1 http://videosite.com/id1" . PHP_EOL .
         "Movie 1 http://videosite.com/id2" . PHP_EOL .
         "Movie 2 http://videosite.com/id3";

$arrLinks = array();
preg_match_all('%(.*)\shttp://videosite\.com/(\w+)\r{0,1}%', $matchWith, $result, PREG_SET_ORDER);
for ($matchi = 0; $matchi < count($result); $matchi++) {
    $arrLinks[$result[$matchi][1]][] = $result[$matchi][2];
}

foreach ($arrLinks as $movieName => $arrMovieIds) {
    print '<div>' . $movieName . '</div>';
    foreach ($arrMovieIds as $movieId) {
        print '<a href="http://videosite.com/'.$movieId.'">Hyperlink</a><br/>';
    }
}
?>
$matchwith = "Part 1 http://videosite.com/id1-1 Part2 http://videosite.com/id1-2";
preg_match_all('/videosite\.com\/(\w+-\d+)/i', $matchwith, $matches);  
foreach($matches[1] as $value)
{  
  print '<a href="http://videosite.com/'.$value.'">Hyperlink</a>';           
}   

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM