joshis Posted July 16, 2010 Share Posted July 16, 2010 I have a html string that contain 'many' links like <a href="http://www.google.co.in/search?hl=en&client=firefox-a&hs=yOP&rls=org.mozilla%3Aen-US%3Aofficial&q=regular+expression+replace+long+links&aq=f&aqi=&aql=&oq=&gs_rfai=">http://www.google.co.in/search?hl=en&client=firefox-a&hs=yOP&rls=org.mozilla%3Aen-US%3Aofficial&q=regular+expression+replace+long+links&aq=f&aqi=&aql=&oq=&gs_rfai=</a> I want this link to be replaced with <a href="http://www.google.co.in/search?hl=en&client=firefox-a&hs=yOP&rls=org.mozilla%3Aen-US%3Aofficial&q=regular+expression+replace+long+links&aq=f&aqi=&aql=&oq=&gs_rfai=">http://www.google.co.in/search...</a> that is link text is shrink to limited no (30) chars. I am not good at regx. Can any one please help? Quote Link to comment Share on other sites More sharing options...
bh Posted July 16, 2010 Share Posted July 16, 2010 If it is not necessary (IMO) you dont have to use Regexp at all costs. If your links always likes <a href="...">...</a> than use substr. Quote Link to comment Share on other sites More sharing options...
.josh Posted July 16, 2010 Share Posted July 16, 2010 $content = "..."; // content here $content = preg_replace("~(<a[^>]+>)([^>]{1,30})[^>]*(</a>)~i",'$1$2...$3',$content); edit: fixed variable names.. Quote Link to comment Share on other sites More sharing options...
joshis Posted July 16, 2010 Author Share Posted July 16, 2010 Thanks Crayon Violent, Its working fine. Quote Link to comment Share on other sites More sharing options...
.josh Posted July 16, 2010 Share Posted July 16, 2010 One caveat I noticed is that it will add the "..." to text shorter than 30 chars... also this is slightly better (meant to do < in stead of > in the 2nd and 3rd char classes) $content = $link; // content here $content = preg_replace("~(<a[^>]+>)([^<]{1,30})[^<]*(</a>)~i",'$1$2...$3',$content); Quote Link to comment Share on other sites More sharing options...
joshis Posted July 21, 2010 Author Share Posted July 21, 2010 Thanks for your help. I have small tweek as you mensioned on last post, Itried last one but it doesn't work for me. For every link text it appends three dots (...) regardless of the total no of chars. For example <a href="http://site.com">site</a> it returns a href="http://site.com">site...</a> it should be <a href="http://site.com">site</a> Only for link texts with length more than 30 i require ... Any help is greatly appreatiated. 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.