Dear I have a clasicfied site.. which let people post anythings they want .. some posting they include too many links in the post .. it have content but if too many link will look like spam .. I want to limit number of link on each post, eg: keep 5 fist links but other than will be remove ( just keep text ) Usualy i use preg_replace("/\<a(.*)\>(.*)\<\/a\>/iU", "$2", $string); or preg_replace("/\<a([^>]*)\>([^<]*)\<\/a\>/i", "$2", $string); PHP: but that function will remove all links .. any way to count the link then strip all links affter links number 5th thanks for any help regards
Instead I would recommend showing an error that the entry made by user contains more than allowed links and he should remove extra links. Let user give liberty to decide what links he wants to keep and which to remove. This will not only make it simpler but make it more convenient for both user and you.
I think this example will help you: <?php $string = 'The text with links'; preg_match_all("/(<a.*>)(.*)(<\/a>)/ismU",$string,$matches,PREG_SET_ORDER); if(count($matches)>5){ for($i=5; $i<count($matches); $i++){ $string = str_replace($matches[$i][0],$matches[$i][2],$string); } } echo($string); ?> PHP:
I agree with mastermunj about returning the form to the user and giving them a chance to make the changes themselves. Failing that, I would forget about regex here, and use SimpleXML instead. You can use the xpath function to return an array of references to all of the links, then replace the nodes for anything more than 5 links with the nodeValue of each reference. Using SimpleXML will give you the added benefit of making sure their links are well formed.