I'm working on a social networking site. When sending a notification, you for example could type [user:20:name] in the notification as a developer in the text you send. So say i send
"[user:20:name] commented on your [video:8:name,link] video"
it would show up as "Bob commented on your iOS 5 review video".
So it would see user, see the user id and that i wanted the name, it would then do the work in the database it needs and replace [user:20:name] in the string with Bob.
For the video it would know i wanted the name for video 8 as a link. How would i parse something like this? I already know how to grab data from the database. Just stuck on t开发者_StackOverflowhis part. Any idea how?
One of the idea was to get each [markup] by its self, and do the parsing on each one, then str_replace it when i get the processed version of the markup.
Not sure how i would get each [markup] by it self.
Not sure if this is too simple, it doesn't deal with multiple tags in a string but you could try something like this as a starting point:
<?php
// the original string
$str = 'User [user:20:name] did foo bar.';
// find the tag
preg_match('/(?<=\[)[a-z0-9:]+(?=\])/', $str, $tags);
// build a db query
list($table, $id, $field) = explode(':', $tags[0]);
$sql = sprintf('SELECT %s FROM %s WHERE id = %d', $field, $table, $id);
// DB query... returns user 'Bob'
$user = 'Bob';
// replace the original tag with the user's name
$output = preg_replace('/\[user:\d+:name\]/', $user, $str);
Update
For multiple tags you could use preg_match_all()
and then iterate over the $tags
array, probably using the $table
variable as a key to build an array of query data... you'd have to decide on the most efficient way to use this data to query your database, based on your database implementation. if you can use PDO prepared statements might be good. so would caching your output because you don't want to preg match and replace all your output every time... or just perform this operation one time and store the output in the database.
Do you mean something like this?
<?php
$string = "[video:8:name,link]";
$string = trim($string, "[]");
$videoMetaData = explode(",", $string);
$nameArray = explode(":", $videoMetaData[0]);
$name = $nameArray[2];
$link = $videoMetaData[1];
echo "<a href='".$link."'>".$name."</a>";
精彩评论