Parsing sMention Form Data On Server In PHP


In my previous post, I introduced the sMention jQuery plugin – a plugin that adds the @mentions to a input element. But I haven’t told in the post how to handle the data on the server side after the form has been submitted. This handling replaces the @mentions to the user’s name in a[href] tag. It’s made possible using smention function bind as the callback function of preg_replace_callback. This smention function can be seen on the file comps/config.php in the Open Repository.

The form’s data is searched for the @ character. The callback function is smention. The following line will set the callback :

$data=preg_replace_callback(“/@(.*?)(s|z)/”, function($match) use ($data){return smention($match,data);},$data);

where $data is the input data. An Example input data :

@1 Google is the best search engine ever.

The above data when parsed using smention function will return the data as (in my case [Open]) :

Subin Siby Google is the best search engine ever.

Here’s the code I used on Open (http://open.subinsb.com) :

function smention($s,$t){

 $userid=$t[1];

 $nxs=strpos($s,”@$userid”);

 $nxs=strlen(“@$userid”)+$nxs;

 $nxs=substr($s,$nxs,1);

 global$db;

 $sql=$db->prepare(“SELECT name FROM users WHERE id=?”);

 $sql->execute(array($userid));

 if($sql->rowCount()==0){

  return”@$userid”.$nxs;

 }else{

  while($r=$sql->fetch()){

   $name=$r[‘name’];

  }

  $html=”@$name”.$nxs;

  return$html;

 }

}

$data=$_POST[‘data’];

$data=preg_replace_callback(“/@(.*?)(s|z|[^0-9])/”, function($t) use ($s){return smention($s,$t);},$s);

You can see the whole smention function at https://github.com/subins2000/open/blob/master/comps/config.php