0

I have PHP code which shows post text. Sometimes this post text content contains user mentions like @[2] where 2 is the serial number of the row for the mentioned user in the user table in my database. Suppose this user has username @mark.

I want to replace this mention code @[2] with a user profile link, for example <a href="https://example.com/mark">@mark</a>

Like take value 2 from @[2] string. This value is a variable Find respected row in user table in database for Show username and user profile link instead of @[2].

4

1 Answer 1

1

For the string replacement trick, you'd usually use preg_replace_callback.
The weirdo @[2] placeholder can be matched with a regex like:

/@\[(\d+)\]/
# ↑   ↑   ↑
#@ [ num  ]

And then you do your link mapping in the callback:

$texty = preg_replace_callback(
     "/@\[(\d+)\]/",
     function($m) {
         return "<a href='/profile?id=$m[1]'>" . user_id_to_name($m[1]) . "</a>";
     }
     $texty
);

Obviously with the appropriate id→name lookup function for your database.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.