问题
On our forum we currently replace all youtube links with embedded objects, thanks to the following answer:
How do I find all YouTube video ids in a string using a regex?
The trouble is, many of our users wish to post a link directly to a particlar time within a video. E.g.:
http://www.youtube.com/watch?v=jECIv7zlD4c&feature=player_embedded#t=1m15s
Note the "#t=1m15s"
As per the youtube documentation, when you are embedding a start time into a video requires a 'start' parameter, you can't use the '1m15s' string. 'start' is a value based on the number of seconds.
<object width="425" height="344">
<param name="movie" value="http://www.youtube.com/v/jECIv7zlD4c?fs=1&start=75"</param>
<param name="allowFullScreen" value="true"></param>
<param name="allowScriptAccess" value="always"></param>
<embed src="http://www.youtube.com/v/jECIv7zlD4c?fs=1&start=75"
type="application/x-shockwave-flash" allowscriptaccess="always" width="425" height="344">
</embed>
</object>
Is their a way to replace '#1m15s' in regex with '&start=75'?
If not, how would you suggest it would be done with PHP so it will recursivly build the objects in a forum post (sometimes people post multiple youtube video links)?
回答1:
preg_replace
is used to manipulate string. In your case you have to make some stuff before replacing.
Maybe you should try to use instead preg_replace_callback
, giving a callback that will make the calculation (X * 60 + Y).
function sumMinSec($matches)
{
$minSecMatches = array();
preg_match("/([0-9]*)m([0-9]*)s/", $matches[0], $minSecMatches);
return "&start=" . ($minSecMatches[1] * 60 + $minSecMatches[2]);
}
and then call something like:
$url = "http://www.youtube.com/v/jECIv7zlD4c?fs=1#1m23s";
echo preg_replace_callback("/#([0-9]*m[0-9]*s)/", "sumMinSec", $url);
Then the result is:
http://www.youtube.com/v/jECIv7zlD4c?fs=1&start=83
来源:https://stackoverflow.com/questions/15147993/youtube-embedded-video-pregreplace-with-start-timing