gitlez

YA: Formatting Inputted Tags

Jul 4th, 2011
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.68 KB | None | 0 0
  1. <?php
  2.  
  3. /*
  4.     Question (http://answers.yahoo.com/question/index?qid=20110704124838AADcKlm):
  5.     I am making a website (using html css and php) in which a person can enter many tags into a single string. Then I need to make each tag into a click-able link. Does anyone know how to do that?
  6.  
  7.     User enters tags in a form => tags are saved into $tags => each individual tag is made into a click-able link
  8.     soda coke bottle new => $tags="soda coke bottle new" => <a href="">soda</a>...
  9.    
  10. */
  11.  
  12.  
  13. $tagDelimiter = ';'; // The character used to seperate tags. eg: ; or , or [space]. Keep in mind that using a space will not allow for two word tags, like New York or Los Angeles or etc.
  14. $linkTemplate = '<a href="find_tags.php?tag=%s">%s</a><br />';
  15. if($_SERVER['REQUEST_METHOD'] === 'POST'){ // If the form has POSTed to the page
  16.     $tags = explode($tagDelimiter,trim($_POST['tags'],$tagDelimiter . ' ')); // Take the tags input and separate them into an array, using the delimiter as the marker to split the line.
  17.     $tags = array_map('trim',$tags); // Cycle through each tag, cleaning the whitespace from either end of the tag.
  18.     $c = count($tags); // Count the number of tags and store it in the variable $c
  19.     $output = '';
  20.     for($i=0;$i<$c;++$i){ // Cycle through the tags and create an $output var containing the HTML.
  21.         $output .= sprintf($linkTemplate, urlencode($tags[$i]), $tags[$i]);
  22.     }
  23.     echo $output;
  24. }else{
  25.     echo '
  26.        <h3>Please use a \'' . $tagDelimiter . '\' to separate the tags</h3>
  27.        <form method="POST">
  28.            <input type="text" name="tags" /><br />
  29.            <input type="submit" value="Format Tags" />
  30.        </form>
  31.    ';
  32. }
  33. ?>
Advertisement
Add Comment
Please, Sign In to add comment