Simple Regular Expression Search and Replace

Discussion in 'PHP' started by ColorWP.com, Apr 27, 2010.

  1. #1
    I have a string that contains text-based links to all kinds of YouTube videos like so:
    All this is inside the variable $post.

    How do I replace all occurances of Youtube links (like http://www.youtube.com/watch?v=WKwRTqB8nY8), with a custom embed code I have (that has to include the Youtube link in a couple of places itself). For example:
    <script type='text/javascript' src='swfobject.js'></script>
     
    <div id='mediaspace'>This text will be replaced</div>
     
    <script type='text/javascript'>
      var so = new SWFObject('player.swf','mpl','470','320','9');
      so.addParam('allowfullscreen','true');
      so.addParam('allowscriptaccess','always');
      so.addParam('wmode','opaque');
      so.addVariable('file','http://www.youtube.com/watch?v=WKwRTqB8nY8');
      so.write('mediaspace');
    </script>
    Code (markup):
    Note: as you probably noticed, the Youtube link is still found inside the above code.

    This needs to be working dynamically, meaning it should not matter how much Youtube links are inside the post.

    Regards!
     
    ColorWP.com, Apr 27, 2010 IP
  2. bytes

    bytes Peon

    Messages:
    39
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Try this:
    I have not tested this, so most likely the regexp won't work out of the box :) but the idea is taking all starting with http://youtube.com...... and up to the first space, that's why you should note the space after the closing brace and replace it with your text with \1 as the content matched inside ()

    
    <?php
    $pattern ='/(http:\/\/youtube\.com\/[\s\S]*?) /im'; //note the space after the closing bracket
    $replace = "<script type='text/javascript' src='swfobject.js'></script>
     
    <div id='mediaspace'>This text will be replaced</div>
     
    <script type='text/javascript'>
      var so = new SWFObject('player.swf','mpl','470','320','9');
      so.addParam('allowfullscreen','true');
      so.addParam('allowscriptaccess','always');
      so.addParam('wmode','opaque');
      so.addVariable('file','\1');
      so.write('mediaspace');
    </script>";
    preg_replace($pattern, $replace, $string); // where $string is your text
    
    PHP:
     
    bytes, Apr 27, 2010 IP
  3. ColorWP.com

    ColorWP.com Notable Member

    Messages:
    3,120
    Likes Received:
    100
    Best Answers:
    1
    Trophy Points:
    270
    #3
    Thank you for your code bytes, but what it did was simply removing all text and leaving the plain Youtube link.
     
    ColorWP.com, Apr 28, 2010 IP
  4. bytes

    bytes Peon

    Messages:
    39
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #4
    ok, pls try:
    
    <?php
    $string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin et nulla eros. Mauris et risus eu tellus facilisis varius. Donec felis eros, rhoncus non facilisis quis, tristique id purus. Fusce turpis tellus, mattis eu fermentum a, dictum condimentum libero. Proin quis ligula felis. Mauris accumsan ullamcorper quam sit amet euismod. In accumsan nunc nec dui auctor semper. Nunc viverra gravida nisi sit amet mollis. Aliquam dictum tempor eros sed pretium. Nullam ullamcorper dapibus orci porta tempus. Aliquam semper vulputate orci, a fermentum mauris volutpat sit amet. Integer dictum scelerisque lectus, et fringilla purus porta ut. Quisque ut metus in est laoreet aliquam ut quis ante. Fusce venenatis odio at lorem aliquet interdum. Pellentesque eu sapien id dui accumsan venenatis vitae nec mi. Nullam iaculis bibendum diam, at pellentesque mauris malesuada non. Donec diam quam, cursus sed tincidunt vitae, tristique quis arcu. In sed magna vitae quam luctus vehicula. Cras vestibulum metus vel augue dictum id dapibus velit tempor.
    
    http://www.youtube.com/watch?v=WKwRTqB8nY8
    
    Morbi eleifend, odio at iaculis blandit, tellus justo mattis dui, at gravida purus neque non urna. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget quam leo. Aenean tempor dolor sed tellus imperdiet posuere. Praesent vitae auctor dolor. In urna tortor, semper non bibendum vitae, imperdiet id nibh. Cras blandit iaculis nulla, eget fringilla eros vehicula eu. Aliquam consectetur pulvinar ipsum ut placerat. Phasellus ac risus id magna bibendum posuere. Pellentesque vitae tristique sem. Duis et nisl id massa tincidunt molestie. Suspendisse non mauris in lacus vulputate pharetra. Sed velit diam, molestie in iaculis vel, sagittis id mi. Phasellus tempus, nulla et rhoncus eleifend, sapien nisl dapibus lectus, in rutrum dui ante nec nunc. Donec molestie, tortor sed tristique interdum, leo sem tempor est, id scelerisque eros nunc et justo. Vivamus suscipit, diam a iaculis pellentesque, odio ligula tempor turpis, vitae vestibulum nulla sem sit amet tellus. Phasellus aliquet sollicitudin felis tristique consequat. ';
    
    
    $pattern ="/(http:\/\/www\.youtube\.com\/\S*?)\s/im"; //note the space after the closing bracket
    $replace = "<script type='text/javascript' src='swfobject.js'></script>
     
    <div id='mediaspace'>This text will be replaced</div>
     
    <script type='text/javascript'>
      var so = new SWFObject('player.swf','mpl','470','320','9');
      so.addParam('allowfullscreen','true');
      so.addParam('allowscriptaccess','always');
      so.addParam('wmode','opaque');
      so.addVariable('file','\\1');
      so.write('mediaspace');
    </script>";
    
    $result = preg_replace($pattern, $replace, $string);
    
    
    
    PHP:
     
    bytes, Apr 28, 2010 IP
  5. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #5
    Use $0 anywhere else in the template you want the URL to show up. I see you mentioned "a few places", but I only see one place in the example.

    You might notice I replaced the single-quotes with double-quotes inside your replacement string. I did this to make using $0 in the replacement string simpler. If you wrap the replacement string with double-quotes instead of the single-quotes I used the $0 wants to be interpreted as a variable before preg_replace ever executes and it just gets to be all screwy from there.

    $template = '<script type="text/javascript" src="swfobject.js"></script>
     
    <div id="mediaspace">This text will be replaced</div>
     
    <script type="text/javascript">
      var so = new SWFObject("player.swf","mpl","470","320","9");
      so.addParam("allowfullscreen","true");
      so.addParam("allowscriptaccess","always");
      so.addParam("wmode","opaque");
      so.addVariable("file","$0");
      so.write("mediaspace");
    </script>';
    
    $str = preg_replace('#http://www\.youtube\.com/\S+#i', $template, $post);
    Code (php):
     
    joebert, Apr 28, 2010 IP
  6. ColorWP.com

    ColorWP.com Notable Member

    Messages:
    3,120
    Likes Received:
    100
    Best Answers:
    1
    Trophy Points:
    270
    #6
    Thank you guys, the first version worked fine for me, but now I've gotten into another problem.

    Inside the replace template I want to include the processed Youtube URL, so it becomes like this:
    $url = "http://www.youtube.com/watch?v=agFBBuOJeKk"; // original Youtube link
    $url = explode("v=",$url,2); // divide the original URL into two parts, separated by "v="
    $url = $url[1]; // get only the Youtube ID (agFBBuOJeKk in the example)
    $url = "http://i4.ytimg.com/vi/".$url."/hqdefault.jpg"; // get the final Youtube thumbnail link to use in the template
    PHP:
    So in the end I want the link (as an example): http://www.youtube.com/watch?v=WKwRTqB8nY8

    To be translated into this code:
    <script type='text/javascript' src='swfobject.js'></script>
     
    <div id='mediaspace'>This text will be replaced</div>
     
    <script type='text/javascript'>
      var so = new SWFObject('player.swf','mpl','470','320','9');
      so.addParam('allowfullscreen','true');
      so.addParam('allowscriptaccess','always');
      so.addParam('wmode','opaque');
      so.addVariable('file','http://www.youtube.com/watch?v=WKwRTqB8nY8');
      so.addVariable('image','http://i4.ytimg.com/vi/WKwRTqB8nY8/hqdefault.jpg');
      so.write('mediaspace');
    </script>
    Code (markup):
    I know how to do the processing on a single string, but I don't know how to do it inside the preg_replace function, because there are all kinds of matches like \\1 and $0 that I don't understand.
     
    ColorWP.com, Apr 29, 2010 IP
  7. bytes

    bytes Peon

    Messages:
    39
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #7
    try this out. I've not checked it, so it might not work, you'd need to modify the regexp:
    
    <?php
    $string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin et nulla eros. Mauris et risus eu tellus facilisis varius. Donec felis eros, rhoncus non facilisis quis, tristique id purus. Fusce turpis tellus, mattis eu fermentum a, dictum condimentum libero. Proin quis ligula felis. Mauris accumsan ullamcorper quam sit amet euismod. In accumsan nunc nec dui auctor semper. Nunc viverra gravida nisi sit amet mollis. Aliquam dictum tempor eros sed pretium. Nullam ullamcorper dapibus orci porta tempus. Aliquam semper vulputate orci, a fermentum mauris volutpat sit amet. Integer dictum scelerisque lectus, et fringilla purus porta ut. Quisque ut metus in est laoreet aliquam ut quis ante. Fusce venenatis odio at lorem aliquet interdum. Pellentesque eu sapien id dui accumsan venenatis vitae nec mi. Nullam iaculis bibendum diam, at pellentesque mauris malesuada non. Donec diam quam, cursus sed tincidunt vitae, tristique quis arcu. In sed magna vitae quam luctus vehicula. Cras vestibulum metus vel augue dictum id dapibus velit tempor.
    
    http://www.youtube.com/watch?v=WKwRTqB8nY8
    
    Morbi eleifend, odio at iaculis blandit, tellus justo mattis dui, at gravida purus neque non urna. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget quam leo. Aenean tempor dolor sed tellus imperdiet posuere. Praesent vitae auctor dolor. In urna tortor, semper non bibendum vitae, imperdiet id nibh. Cras blandit iaculis nulla, eget fringilla eros vehicula eu. Aliquam consectetur pulvinar ipsum ut placerat. Phasellus ac risus id magna bibendum posuere. Pellentesque vitae tristique sem. Duis et nisl id massa tincidunt molestie. Suspendisse non mauris in lacus vulputate pharetra. Sed velit diam, molestie in iaculis vel, sagittis id mi. Phasellus tempus, nulla et rhoncus eleifend, sapien nisl dapibus lectus, in rutrum dui ante nec nunc. Donec molestie, tortor sed tristique interdum, leo sem tempor est, id scelerisque eros nunc et justo. Vivamus suscipit, diam a iaculis pellentesque, odio ligula tempor turpis, vitae vestibulum nulla sem sit amet tellus. Phasellus aliquet sollicitudin felis tristique consequat. ';
    
    
    $pattern ="/http:\/\/www\.youtube\.com\/watch\?v=(\S*?)\s/im"; 
    $replace = "<script type='text/javascript' src='swfobject.js'></script>
     
    <div id='mediaspace'>This text will be replaced</div>
     
    <script type='text/javascript'>
      var so = new SWFObject('player.swf','mpl','470','320','9');
      so.addParam('allowfullscreen','true');
      so.addParam('allowscriptaccess','always');
      so.addParam('wmode','opaque');
      so.addVariable('file','http://youtube.com/watch?v=\\1');
    so.addVariable('image','http://i4.ytimg.com/vi/\\1/hqdefault.jpg');
      so.write('mediaspace');
    </script>";
    
    $result = preg_replace($pattern, $replace, $string);
    
    PHP:
     
    bytes, Apr 29, 2010 IP
    www.Andro.ws likes this.