views:

207

answers:

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

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"&gt;www.youtube.com/watch?v=2bP9tRhJRTw&lt;/a&gt;

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"&gt;www.youtube.com/watch?v=2bP9tRhJRTw&lt;/a&gt; russel peters video blah blah. Turtles: <a href="http://turtles.com"&gt;turtles.com&lt;/a&gt;";


$preurl = "Russel Peter video: ";

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

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

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

THANK YOU FOR YOUR HELP

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

A: 

You can use explode($tags, ' ', 2); to get an array of two elements, the first being the first tag (the URL) and the second being all the other tags, if you know for sure they're always going to be space-separated.

zneak
+2  A: 
$orgstring = 'Russel Peter video: <a rel="nofollow" href="http://www.youtube.com/watch?v=2bP9tRhJRTw"&gt;www.youtube.com/watch?v=2bP9tRhJRTw&lt;/a&gt; russel peters video blah blah. Turtles: <a href="http://turtles.com"&gt;turtles.com&lt;/a&gt;';
$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"&gt;turtles.com&lt;/a&gt;
ghostdog74
it looks good, but i accidentally put the code in <quotes> instead of <code>Could you please please please update your original answer with the update variables?THANK YOU!
jiexi
thank you good sir
jiexi