如何在 PHP 中创建 Wordpress 短代码样式的函数 [英] How to create a Wordpress shortcode-style function in PHP

查看:22
本文介绍了如何在 PHP 中创建 Wordpress 短代码样式的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 PHP 中创建 Wordpress 短代码样式功能,以用图像替换诸如[[133]]"之类的短代码.基本上,我有一个包含 ID 为 1-150 的图像 URL/标题/字幕的 MySQL 表,我希望能够使用如下短代码将它们动态插入到我的页面文本中:

I am trying to create a Wordpress shortcode-style feature in PHP to replace shortcodes like "[[133]]" with images. Basically, I have a MySQL table of image URLs/titles/subtitles with IDs 1-150, and I want to be able to dynamically insert them into the text of my pages with shortcodes like this:

布拉布拉布拉布拉布拉布拉布拉.[[5]] 另外,bla bla bla bla bla [[27]]嘿,还有bla bla bla![[129]]

所以,我只想获取 ID 作为 $id,然后将其提供给 MySQL 查询,例如mysql_query("SELECT title,subtitle,url FROM images WHERE id = $id")然后用 img/title/subtitle 替换[[id]]".我希望能够在同一页面上多次执行此操作.

So, I just want to grab the ID as $id, and then feed it to a MySQL query like mysql_query("SELECT title,subtitle,url FROM images WHERE id = $id") and then replace the "[[id]]" with the img/title/subtitle. I would like to be able to do this multiple times on the same page.

我知道这必须涉及正则表达式和 preg_match、preg_replace、strstr、strpos、substr 的某种组合……但我不知道从哪里开始以及我应该使用哪些函数来做哪些事情.你能推荐一个策略吗?我不需要代码本身——只要知道对哪些部分使用什么就会非常有帮助.

I know this has to involve regex and some combination of preg_match, preg_replace, strstr, strpos, substr... but I don't know where to start and which functions I should be using to do which things. Can you recommend a strategy? I don't need the code itself—just knowing what to use for which parts would be extremely helpful.

推荐答案

使用函数 getimage($id) 执行 MySQL 查询并格式化替换文本,这几乎 满足您的一切需求:

With a function getimage($id) that does the MySQL query and formats the replacement text, this almost does everything you need:

$text = "Blabla [[5]] and [[111]] bla bla bla [[27]] and bla bla bla! [[129]]";

$zpreg = preg_match_all('#\[\[(\d{1,3})\]\]#', $text, $matches );

var_dump( $matches[1] );  

$newtext = preg_replace('#\[\[(\d{1,3})\]\]#', getimage($matches[1][?????]), $text);

echo $newtext;

我只需要弄清楚在 getimage() 里面放什么(其中 ????? 是),这将使它为正确的 [[id]].

I just need to figure out what to put inside getimage() (where ????? is) that will make it put in the right image for the right [[id]].

参考preg_match_allpreg_replace 有关更多详细信息,请参阅官方文档.

Refer preg_match_all and preg_replace on official documentation for more details.

这篇关于如何在 PHP 中创建 Wordpress 短代码样式的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆