开发者

PHP return preg_replace() inside of foreach?

开发者 https://www.devze.com 2023-02-11 06:33 出处:网络
hey, i have no idea what I\'m doing wrong. I have a regexp pattern that looks for a youtube url inside or [track=url].

hey, i have no idea what I'm doing wrong. I have a regexp pattern that looks for a youtube url inside or [track=url].

I'm returning a youtube embed-code if the regexp is matched. I need to have a unique ID for each video. I'm creating this ID with a simple count variable inside my preg_match_all foreach loop.

The $uniqueID that I need for each video works just fine. If I have 3 [track=url] inside my $content I get 3 different id's echoed out (player_1, player_2, player_3, etc...)

However ONLY MAJOR PROBLEM that I have is that I have no idea how I'm using the preg_replace in that case. I need to return the embedCode for each video with each the unique ID that I'm creating.

<?php

    $youtubeUrl = "/(\[TRACK=)((http|https)(\:\/\/)(www|it|co\.uk|ie|br|pl|jp|fr|es|nl|de)(\.youtube\.)(com|it|co\.uk|ie|br|pl|jp|fr|es|nl|de)([a-zA-Z0-9\-\.\/\?_=&;]*))(\])/si";

    $search = preg_match_all($youtubeUrl, $content, $matches, PREG_OFFSET_CAPTURE);
    $i = 0;

    foreach ($matches[8] as 开发者_StackOverflow社区$match) {

        $watch = $match[0];

        //unique id
        $uniqueID = "player_" . $i; // player_0, player_1, player_2 ...

        //final video url
        $video = $uri . $watch;

        echo $video . "<br/>"; //correct 3 times different

        $content = preg_replace($youtubeUrl, embedCode($video, $uniqueID), $content);
        // three times player_0

        $i++;
    }

    //$content = preg_replace($youtubeUrl, embedCode($video, $uniqueID), $content);
    // three times player_3

    return $content;

?>

Any idea what I need to do here? I'm helpless! If I call the preg_replace inside the loop I get three times the embed_code for player_0, if I call it outside the foreach loop I get three time player_3.

What am I doing wrong here! Thank you very much for your help.


You should not manually loop over the match results and afterwards run a second preg_replace. That's a perfect use case for preg_replace_callback to simplify things:

$i = 0;
$content = preg_replace_callback($rx_youtubeUrl, "cb3", $content);

function cb3 ($match) {

    $watch = $match[8];
    global $i, $uri;
    $i++;

    //unique id
    $uniqueID = "player_" . $i; // player_0, player_1, player_2 ...

    //final video url
    $video = $uri . $watch;

    return embedCode($video, $uniqueID);
}

For the $uniqueID you might have to use a global or static variable.

That the same ID appeared three times is caused by the preg_replace running over all occurrences of the regex. It doesn't just find the current [TRACK=.., but strips all at once. You could have used a static str_replace alternatively.

0

精彩评论

暂无评论...
验证码 换一张
取 消