문제

What is the best way (or your preferred method) to change this ...

$youtubeVideo = "[youtubeVideo:9bZkp7q19f0]";

into this...

$youtubeVideo = "<iframe width='560' height='315' src='//www.youtube.com/embed/9bZkp7q19f0' frameborder='0' allowfullscreen></iframe>";

I have managed using str_replace but it looks a bit hacky and messy.

도움이 되었습니까?

해결책

Use preg_replace.

<?php
$youtubeVideo = "[youtubeVideo:9bZkp7q19f0]";
$youtubeVideo = preg_replace('/\[(.*?):(.*?)\]/m', '<iframe width=\'560\' height=\'315\' src=\'//www.youtube.com/embed/$2\' frameborder=\'0\' allowfullscreen></iframe>', $youtubeVideo);

echo $youtubeVideo;
//<iframe width='560' height='315' src='//www.youtube.com/embed/9bZkp7q19f0' frameborder='0' allowfullscreen></iframe>
?>

LIVE DEMO

REGEX EXPLANATION

\[(.*?):(.*?)\]

Match the character “[” literally «\[»
Match the regex below and capture its match into backreference number 1 «(.*?)»
   Match any single character that is NOT a line break character (line feed) «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “:” literally «:»
Match the regex below and capture its match into backreference number 2 «(.*?)»
   Match any single character that is NOT a line break character (line feed) «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “]” literally «\]»

<iframe width='560' height='315' src='//www.youtube.com/embed/$2' frameborder='0' allowfullscreen></iframe>

Insert the character string “<iframe width='560' height='315' src='//www.youtube.com/embed/” literally «<iframe width='560' height='315' src='//www.youtube.com/embed/»
Insert the text that was last matched by capturing group number 2 «$2»
Insert the character string “' frameborder='0' allowfullscreen></iframe>” literally «' frameborder='0' allowfullscreen></iframe>»

다른 팁

Using c-style string formatters is easier to read. The %s is replaced by the second argument.

$youtubeVideo = substr($youtubeVideo,14,25); //get id out
sprintf("$youtubeVideo = \"<iframe width='560' height='315' src='//www.youtube.com/embed/%s' frameborder='0' allowfullscreen></iframe>\"", $youtubeVideo);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top