PHP explode () not finding separator

I am creating a blog that needs to parse bbcode tags like this:

Input: <youtube=http://www.youtube.com/watch?v=VIDEO_ID&feature=channel>


Output:

<object width="400" height="245">
<param name="movie" value="http://www.youtube-    nocookie.com/v/VIDEO_ID&hl=en&fs=1&rel=0&showinfo=0"></param>
<param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>
<embed src="http://www.youtube-nocookie.com/v/VIDEO_ID&hl=en&fs=1&rel=0&showinfo=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="400" height="245"></embed>
</object>

      

My function is incredibly simple so far because I'm stuck in the easiest part! Right now I have a main process function that calls the delta functions of the process. In this case, one of them is processYouTubeVideos (). So I call it like this:

$str = eregi_replace('\<youtube=([^>]*)\>', processYouTubeVideos("\\1"), $str);

      

processYouTubeVideos () gets urls from youtube tag fine, but for some reason when using explode () (or split), the delimiter is never found. Even using test values ​​like "u" or "tube" ...

function processYouTubeVideos ($str) {

    $params = explode("?", $str);
    $params = explode("&", $params[1]);

    return $params[0];

}

      

+1


a source to share


2 answers


Try:

$str = preg_replace('/<youtube=([^>]*)>/e', 'processYouTubeVideos("$1")', $str);

      



The code you are trying to run will not work because the function on the output line will be called on the target and not on the output. This means that you are sending "\ 1" literally to the function. Add var_dump($str);

a function to the beginning and try running the code again, and you can see it clearly.

preg_replace has a special "e" flag that you can use to execute the function every time a replacement is made. This works by inserting the subpattern at the marker position ($ 1) and then running something like eval()

or create_function()

in code to execute it and get the result. It is then sent back to preg_replace()

and the actual replacement is done.

+3


a source


The processYouTubeVideos ("\ 1") function runs before eregi_replace.

The following does what I believe it intends to do:



$str = eregi_replace('\<youtube=([^>]*)\>', "\\1", $str);
$str = processYouTubeVideos($str);

      

It performs the replacement and then sends the resulting value to processYouTubeVideos.

0


a source







All Articles