Showing a message based on number of words

Discussion in 'PHP' started by crazyryan, Nov 1, 2007.

  1. #1
    Hi,

    I've got $r['fulldescription'] which stores a long bit of text. Basically I wan't to show two ad blocks in that text.

    I need to show an adblock every 250 words but limit the amount of adblocks to 2.

    Anyone got any ideas, thanks!
     
    crazyryan, Nov 1, 2007 IP
  2. crazyryan

    crazyryan Well-Known Member

    Messages:
    3,087
    Likes Received:
    165
    Best Answers:
    0
    Trophy Points:
    175
    #2
    .. Anyone? thanks
     
    crazyryan, Nov 2, 2007 IP
  3. Oli3L

    Oli3L Active Member

    Messages:
    207
    Likes Received:
    3
    Best Answers:
    1
    Trophy Points:
    70
    #3
    If I understood you right, then you should use substr();
    It helps you to limit the words.
    substr($string,0, number of letters);
     
    Oli3L, Nov 2, 2007 IP
  4. crazyryan

    crazyryan Well-Known Member

    Messages:
    3,087
    Likes Received:
    165
    Best Answers:
    0
    Trophy Points:
    175
    #4
    I don't want to limit the words, I wanna show something every certain amount of words.
     
    crazyryan, Nov 2, 2007 IP
  5. Brewster

    Brewster Active Member

    Messages:
    489
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    60
    #5
    Try this code. It's pretty inefficient, but it does the job.

    <?php
    
    	$string = 'This is a test string with some words in it';
    	$Advert = '{ad}';
    	$Frequency = 4;
    	$WordCounter = 1;
    	
    	$WordArray = explode( ' ', $string );
    	
    	for ( $count = 0 ; $count <= sizeof( $WordArray )-1 ; $count++ )
    	{
    		echo $WordArray[ $count ] . ' ';
    		
    		if ( $WordCounter++ == $Frequency )
    		{
    			$WordCounter = 1;
    			echo $Advert;
    		}
    	}
    
    ?>
    PHP:
    Brew
     
    Brewster, Nov 2, 2007 IP
  6. crazyryan

    crazyryan Well-Known Member

    Messages:
    3,087
    Likes Received:
    165
    Best Answers:
    0
    Trophy Points:
    175
    #6
    Thanks Brewster, I'll try it tomorrow hopefully. I'm off now, cheers.
     
    crazyryan, Nov 2, 2007 IP
  7. exodus

    exodus Well-Known Member

    Messages:
    1,900
    Likes Received:
    35
    Best Answers:
    0
    Trophy Points:
    165
    #7
    
    <?php
    $string = '';
    $advert = '';
    
    function insert_ads($string,$advert)
    {
       $arr = explode(" ",$string);
       if(count($arr) >= 250)
       {
          $arr[249] =  $arr[249].$advert;
       }
    
       if(count($arr) >= 500)
       {
          $arr[499] =  $arr[499].$advert;
       }
       return implode(" ", $arr)
    }
    
    echo insert_ads($string,$advert);
    
    ?>
    
    PHP:
    Not sure if it is the best way, but this is something I would use to do what your asking.
     
    exodus, Nov 3, 2007 IP