treehouse : what would you like to learn today?
Web Design Web Development iOS Development

If status contains @tag then..?

  • All I need is a PHP scripts that detects if the variable "comment" includes any " @username " - and then get that username without the "@" :)

  • $words = explode(" ",$comment);
    foreach ($words as $word) {
    $match = preg_match("/\B@[^\B]+/",$word,$matches);
    if ($match==1) {
    $username = substr($matches[0],1);
    echo $username;
    }
    }
  • Thank's. I did it a bit different:

    <?php
    $comment = "We all know @Schart does like cupcakes";

    if(strstr($comment, '@')){
    $tagafter = strstr($comment, "@");
    /* TAGAFTER = @Schart does like cupcakes */

    $arr = explode(' ', trim($tagafter));
    $tag = $arr[0];
    /* TAG = @Schart */

    $newtag = str_replace('@', '', $tag);
    /* NEWTAG = Schart */

    echo($newtag);
    ?>

  • Your method will only find the first username in a comment though.
  • That is true :)
  • @bungle Long time since this post was active, but I just want to say thank you again, since I went back to this post now after re-making the website and I use this for notifications when someone is tagged. I used your version this time, so much better.