开发者

Mysql query based on string within a preg_match or preg_replace?

开发者 https://www.devze.com 2023-02-03 13:09 出处:网络
In a previous question, I managed to get some text replacement working for my wiki. Which works great with titles. But now I\'d like to replace titles with IDs. For my wiki, I simply replace [[wiki::T

In a previous question, I managed to get some text replacement working for my wiki. Which works great with titles. But now I'd like to replace titles with IDs. For my wiki, I simply replace [[wiki::Title]] with a link to that title. How can I get links from IDs in that title spot?

The below code works, but only outputs the ID. Example text includes [[tdh::1]] and [[tdh::5]]. I would now like to take that ID and query my database for it and use that result to build a link.

$text = preg_r开发者_运维技巧eplace("/\[\[tdh::(.+?)\]\]/","<a href=\"*page here*?task=tdhelp&action=read&id=\\1\">\\1</a>", $text);

Pointing me in the right direction would be helpful. Thanks.


You can use preg_replace_callback and for the callback parameter use a function that uses the ID to fetch the name from the database.

Note that above approach, while simple, could potentially result in a lot of database calls. An improvement is to first find all the IDs using preg_match_all and store them in an array. Then you can fetch all the names in a single database call. The SQL you need will be something like this:

SELECT id, name
FROM links
WHERE id IN (?, ?, ?)

Watch out for SQL injection vulnerabilities if you aren't using parameterized queries. Store the results in an associative array with the ID as the key and the name as the value.

Finally you can use preg_replace_callback where the callback function finds the name from the array.


You should first read the id and any other association necessary from the database and cache them in some sort of array.

The you use a preg_replace_callback to to the actual replacement based on that cached data.

Alternatively you could to a two step process: try once and record the id's found (not replacement). Use those to query the db for additional data. Do another search and replace the results.

You could also do what @Mark suggested but if the page you are editing has 15 title you will make 15 queries to the db and that might work or not for you. In some high load it will probably not work. This means slow pages usually.

0

精彩评论

暂无评论...
验证码 换一张
取 消