user2793161
user2793161

Reputation: 79

PHP tagging system

I have this script:

<?php

    $string = "@Erol Simsir @Hakan Simsir";
    $output = preg_replace("/@([^\s]+)/", "<a href=\"?tag=$1\">$1</a>", $string);
    echo $output;

?>

This script detects all words with a '@' symbol in front of them and changes them into links/tags. However, I don't want a hashtag system but a tagging system, like on Twitter, where you can do '@JohnDoe' and the user JohnDoe will be the person the Tweet goes to.

So, what I need is to store all the tags in a string in an array to use them for a SQL query afterwards.

How can I achieve this?

UPDATE

I have this code right now:

$string  = $_POST["tags"];
$output = preg_replace("/@([^\s]+)/", "<a href=\"?tag=$1\">$1</a>", $string);
$finalOutput = explode(" ", $string);
$count = count($finalOutput);
$i = 0;
while($i < $count) {
echo $finalOutput[$i];
$i = $i + 1;
}

Problem is, that the tags look like this in the output: @john @sandra etc. How can I remove the @ symbol in the output?

Upvotes: 0

Views: 648

Answers (3)

user2793161
user2793161

Reputation: 79

I've seen that there's something wrong with this script:

$string  = $_POST["tags"];
$output = preg_replace("/#([^\s]+)/", "<a href=\"?tag=$1\">$1</a>", $string);
$finalOutput = explode(" ", $output);
$count = count($finalOutput);
$i = 0;
while($i < $count) {
    echo $finalOutput[$i] . "<br />";
    $i = $i + 1;
}

It also explodes all the words without the @ symbol. When I just insert 'JohnDoe' in the form, it accepts that too, but it should only accept text with the @ symbol. So when I insert 'JohnDoe' in the script, it should validate and say that that's not a valid tag. Only when the input goes like '@john @steve' etc it should work.

Upvotes: 0

ncrocfer
ncrocfer

Reputation: 2570

The simplest is to use preg_match_all :

$string = "@Erol Simsir @Hakan Simsir";
preg_match_all("/@(\w+)/", $string, $output);
print_r($output[0]);

Upvotes: 1

Nishant Solanki
Nishant Solanki

Reputation: 2128

$array = explode(' ', $string);

give a try to this code :)

$count = count($array);
$tag_array = array();
$j=0;
for($i=0;$i<$count;$i++)
{
  if(substr($array[$i],0,1)==='@')
  {
    $tag= ltrim ($array[$i],'@');
    $tag_array[$j] = $tag;
    $j++;
  } 
}

print_r($tag_array);

let me know if you want any further help :)

Upvotes: 1

Related Questions