spires Posted October 11, 2012 Share Posted October 11, 2012 Hi I'm pulling my data from a database. I'm trying to grab the first <a> and place it in a String. Any ideas? <a> Tag: <a href="http://lwww.mysite,com"><img alt="" src="/media/lci_strip.png" style="width: 701px; height: 92px; " /></a> What I have so far - but not working: $findImg = preg_match_all('/<a[^</a>]+</a>/i',$cleanMeg, $result); $stripFirstImg = str_replace($result[0][0], "", $cleanMeg); Thanks Quote Link to comment Share on other sites More sharing options...
spires Posted October 11, 2012 Author Share Posted October 11, 2012 Worked it out $findImg = preg_match_all('/<a(.*)<\/a>/i',$cleanMeg, $result); $stripFirstImg = str_replace($result[0][0], "", $cleanMeg); Thanks anyway. Quote Link to comment Share on other sites More sharing options...
Christian F. Posted October 12, 2012 Share Posted October 12, 2012 That RegExp won't do quite what you expect it to, I'm afraid. It'll select everything between the first opening anchor tag, to the last closing anchor tag. So if start with one link, and finish with another, you'll select the entire text. To get what you want you'll have to use this: $RegExp = '#<a[^>]*>[^<]+</a>#i'; The square brackets define a character group, and since I've start them with a caret (^) I've told the RegExp engine that I want everything except the characters in the group. Which is why your first RegExp didn't work, since you only selected up to the first character that matched one of the characters inside the group. To get your first RegExp to work, you would have had to use negative lookahead. www.regular-expressions.info has more information on Regular Expressions, and well worth a read. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.