Sentence to words function (PHP)

Discussion in 'PHP' started by ruud, Aug 2, 2007.

  1. #1
    I'm looking for a mini function like this example;

    ourfunction("our four words sentence") = <a href="/tag/our.html">our</a> <a href="/tag/four.html">four</a> <a href="/tag/words.html">words</a> <a href="/tag/sentence.html">sentence</a>
    PHP:
    Can someone show a function like this?

    Thanks.
     
    ruud, Aug 2, 2007 IP
  2. Vbot

    Vbot Peon

    Messages:
    107
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #2
    function ourfunction($words)
    {
        $word = explode(" ", $words);
        foreach($word as $value)
        {
            //return "<a href='/tab/$value.html'>$value</a> ";
            echo "<a href='/tab/$value.html'>$value</a> ";
        }
    }
    ourfunction("our four words sentence");
    
    PHP:
    That should work.
     
    Vbot, Aug 2, 2007 IP
    ruud likes this.
  3. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #3
    EDIT: A bit too late.


    Like this?
    
    function words2links($text)
    {
    	$output = array();
    	
    	foreach (explode(' ', $text) AS $word)
    	{
    		if ($word = preg_replace('/\W/', null, $word))
    		{
    			$output[] = '<a href="/tag/' . $word . '.html">' . $word . '</a>';
    		}
    	}
    	
    	return implode(' ', $output);
    }
    
    
    
    echo words2links('hello this is a test .');
    
    
    PHP:
     
    nico_swd, Aug 2, 2007 IP
  4. ruud

    ruud Peon

    Messages:
    308
    Likes Received:
    16
    Best Answers:
    0
    Trophy Points:
    0
    #4
    All worked, thanks for your help. Reps added.
     
    ruud, Aug 2, 2007 IP