How to remove number of links from posting if it over limit

Discussion in 'PHP' started by binhaus, Oct 12, 2010.

  1. #1
    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
     
    binhaus, Oct 12, 2010 IP
  2. mastermunj

    mastermunj Well-Known Member

    Messages:
    687
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    110
    #2
    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.
     
    mastermunj, Oct 13, 2010 IP
  3. s_ruben

    s_ruben Active Member

    Messages:
    735
    Likes Received:
    26
    Best Answers:
    1
    Trophy Points:
    78
    #3
    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:
     
    s_ruben, Oct 13, 2010 IP
  4. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #4
    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.
     
    joebert, Oct 13, 2010 IP