I know strip_tags() removes html tags from a string of text. I don't know if striptags can help for my question, but how would I allow 2 <a> tags and remove the 3rd, 4th, 5th, ... <a> tags?

example:

$str= "<b>This text</b> has <a href="#">1 link</a>, a <a href="#">2nd link</a> and a <a href="#">3rd link</a>.";
$str = strip_tags($str, "<a>");
echo $str;

This text has 1 link, a 2nd link and a 3rd link.

How can I make it display this instead?

This text has 1 link, a 2nd link and a 3rd link.

    You could always use [man]strpos/man to find the first offset, then +4 that offset and use [man]strpos/man to find the second, and then [man]substr/man from that offset +4 to the end, then use strip_tags.

    The "+4" is because "</a>" is 4 characters long. So we get the position of the "<" character, then add 4 to move the marker to the character after the ">".

    Something like:

    $string = 'This text has <a href="#">1 link</a>, <a href="#">2nd link</a> and a <a href="#">3rd link</a>.';
    
    $first_link = strpos($string, '</a>');
    $second_link = strpos($string, '</a>', $first_link+1);
    $string1 = substr($string, 0, $second_link+4);
    $string2 = substr($string, $second_link+4);
    
    $string = $string1 . strip_tags($string2);
    echo $string;

      Just because I could:

      $output = preg_replace(
         '#^((?:.*?<a\s.*?</a>){0,2})(.*)$#ise',
         "strip_tags(stripslashes('$1'),'<a>').strip_tags(stripslashes('$2'))", 
         $text
      );
      

        While you are being so generous, could I ask you to write something to check if a string has no <a> tags in it at all? (very important: it can not already have <a> tags)
        When it doesn't have any, make links from all text that starts with http:// (but limit to 2 links)

          Well, to check if it has no "<a>" tags, you could just do a quick:

          if(strpos($string, "<a>") === false)
          {
              // No <a> tag found...
              // Replace http://.... with <a href="http://....">http://....</a>:
              $string2 = preg_replace('~(http://[^\s]+)~i', '<a href="\\1">\\1</a>', $string, 2);
          }

          Something like that could be used. The [man]preg_replace/man pattern(s) may need some tweaking, but that's the basic idea. It will look for the string "http://" with any number of characters after it, so long as it's not a space. So "http://www.phpbuilder.com" would be caught; however, "http:// " would not be. This is merely aesthetic and can easily be changed.

          Hope that helps push you in the right direction.

            Write a Reply...