Search code examples
phpstringurlexplodestrip

PHP Strip string of first url and report results


Russel Peter video: <a rel="nofollow" href="http://www.youtube.com/watch?v=2bP9tRhJRTw">www.youtube.com/watch?v=2bP9tRhJRTw</a> russel peters video blah blah. Turtles: <a href="http://turtles.com">turtles.com</a>

I have a string that contains text and and tags with enclosed urls like the above example.

I want to strip the out ONLY the first tag found

<a rel="nofollow" href="http://www.youtube.com/watch?v=2bP9tRhJRTw">www.youtube.com/watch?v=2bP9tRhJRTw</a>

and from that, strip out the url inside the href="".

But... i also want to be able store the text around the tag that is pulled out.

I'm looking for something like this as the end result after all the stripping:

$originalstring = "Russel Peter video: <a rel="nofollow" href="http://www.youtube.com/watch?v=2bP9tRhJRTw">www.youtube.com/watch?v=2bP9tRhJRTw</a> russel peters video blah blah. Turtles: <a href="http://turtles.com">turtles.com</a>";


$preurl = "Russel Peter video: ";

$atag = "<a rel="nofollow" href="http://www.youtube.com/watch?v=2bP9tRhJRTw">www.youtube.com/watch?v=2bP9tRhJRTw</a>";

$url = "http://www.youtube.com/watch?v=2bP9tRhJRTw";

$afterurl = " russel peters video blah blah. Turtles: <a href="http://turtles.com">turtles.com</a>";

THANK YOU FOR YOUR HELP

NOTE: i apologize if I've used the wrong terms.


Solution

  • $orgstring = 'Russel Peter video: <a rel="nofollow" href="http://www.youtube.com/watch?v=2bP9tRhJRTw">www.youtube.com/watch?v=2bP9tRhJRTw</a> russel peters video blah blah. Turtles: <a href="http://turtles.com">turtles.com</a>';
    $s = explode(":",$orgstring,2);
    $preurl = $s[0];
    $href= explode('href="',$s[1]);
    $url=preg_replace("/\">.*/","",$href[1]);
    $atag = preg_replace("/\">.*/","",$s[1]);
    $after=explode("</a>",$orgstring,2);
    $afterurl=$after[1];
    print "\$preurl: $preurl\n";
    print "\$url: $url\n";
    print "\$atag: $atag\n";
    print "\$afterurl: $afterurl\n";
    

    output

    $ php test.php
    $preurl: Russel Peter video
    $url: http://www.youtube.com/watch?v=2bP9tRhJRTw
    $atag:  <a rel="nofollow" href="http://www.youtube.com/watch?v=2bP9tRhJRTw
    $afterurl:  russel peters video blah blah. Turtles: <a href="http://turtles.com">turtles.com</a>