简体   繁体   中英

Regular Expression (preg_match_all)

I have a private website where I share videos (and some other stuff). What I have achieved is that with preg_match_all() it automatically finds the link and it paste the video with the HTML code to my website.

Here an example:

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

This works. I know this could may could be done easier, but it has to be this way.

But I do not know how this with a two part movie. Here an example:

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

Everything after http://videosite.com/ (...) is unique.

What I want is if you write Part 1 and Part 2 (or whatever) before the link, that it automatically detects it as Part 1 and Part 2 of this video.

$matchwith could contain different movies.

So I believe this is what you need:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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