正则表达式(preg_match_all)

时间:2011-11-22 15:45:54

标签: php regex preg-match 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可能包含不同的电影。

2 个答案:

答案 0 :(得分:1)

所以我相信这就是你所需要的:

<?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/>';
    }
}
?>

答案 1 :(得分:0)

$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>';           
}   
相关问题