如何在 PHP 中创建 WordPress 短代码样式函数

发布于 2024-10-09 16:22:13 字数 506 浏览 4 评论 0原文

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

Blabla bla bla bla bla。 [[5]] 另外,啦啦啦啦啦啦啦[[27]] 嘿,还有布拉布拉布拉! [[129]]

所以,我只想获取 ID 作为 $id,然后将其提供给 MySQL 查询,例如 mysql_query("从图像中选择标题、副标题、url,其中 id = $id") 然后将“[[id]]”替换为图片/标题/副标题。我希望能够在同一页面上多次执行此操作。

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

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:

Blabla bla bla bla bla. [[5]] Also, bla bla bla bla bla [[27]]
Hey, and bla bla bla! [[129]]

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.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

她说她爱他 2024-10-16 16:22:13

如果您希望能够编写这样的短代码:

[[function_name_suffix parameter1 parameter2 ...]]

这里有一个更完整的方法,使用 preg_replace_callbackcall_user_func_array 来实现参数化短代码。

function shortcodify($string){
    return preg_replace_callback('#\[\[(.*?)\]\]#', function ($matches) {
        $whitespace_explode = explode(" ", $matches[1]);
        $fnName = 'shortcode_'.array_shift($whitespace_explode);
        return function_exists($fnName) ? call_user_func_array($fnName,$whitespace_explode) : $matches[0];
    }, $string);
}

如果定义了这个函数:

function shortcode_name($firstname="",$lastname=""){
    return "<span class='firstname'>".$firstname."</span> <span class='lastname'>".$lastname."</span>";
}

那么这个调用

print shortcodify("My name is [[name armel larcier]]");

将输出:

My name is <span class='firstname'>armel</span> <span class='lastname'>larcier</span>

这只是我现在基于 supertrue 的想法实现的东西。

任何反馈都非常受欢迎。

If you want to be able to write shortcodes like this :

[[function_name_suffix parameter1 parameter2 ...]]

here is a more complete way, using preg_replace_callback and call_user_func_array to implement parameterized shortcodes.

function shortcodify($string){
    return preg_replace_callback('#\[\[(.*?)\]\]#', function ($matches) {
        $whitespace_explode = explode(" ", $matches[1]);
        $fnName = 'shortcode_'.array_shift($whitespace_explode);
        return function_exists($fnName) ? call_user_func_array($fnName,$whitespace_explode) : $matches[0];
    }, $string);
}

If this function is defined :

function shortcode_name($firstname="",$lastname=""){
    return "<span class='firstname'>".$firstname."</span> <span class='lastname'>".$lastname."</span>";
}

Then this call

print shortcodify("My name is [[name armel larcier]]");

Will output :

My name is <span class='firstname'>armel</span> <span class='lastname'>larcier</span>

This is just something I implemented right now based on supertrue's idea.

Any feedback is more than welcome.

知足的幸福 2024-10-16 16:22:13

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

$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]] 的正确图像中。

参考 preg_match_all< /a> 和 preg_replace 有关更多详细信息,请参阅官方文档。

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;

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]].

Refer preg_match_all and preg_replace on official documentation for more details.

錯遇了你 2024-10-16 16:22:13

为此,可以采取各种不同的方法,具体取决于您打算如何显示等,

以句子“Hello [34] world”为例,

创建一个简单的函数,例如replaceCode($string)

function replaceCode($string){

    $pos = strpos($string, '['); // Find the first occurrence of the bracket

    if($pos != false){

          // If everything is ok take the next 2 numbers from it

          // Check for a close bracket & remove ]

          // call another function to replace the number with the image text

    }




}

如果发现更多出现的括号,则递归调用该函数再次将字符串的其余部分再次传递给函数。

注意:可能需要首先进行验证以确保 [ 和 ] 正确平衡!

Various different approaches can be taken for this, depending on how you plan to display ect,

Take the sentence "Hello [34] world"

Create a simple function e.g replaceCode($string)

function replaceCode($string){

    $pos = strpos($string, '['); // Find the first occurrence of the bracket

    if($pos != false){

          // If everything is ok take the next 2 numbers from it

          // Check for a close bracket & remove ]

          // call another function to replace the number with the image text

    }




}

If anymore occurrences of brackets are found, recursively call the function again, passing the rest of the string to the function again.

Note: Validation may need to be done first to ensure the [ and ] are properly balanced!

晨与橙与城 2024-10-16 16:22:13

我的赌注是 PHP 的 strtr 函数...

<?php
function get_profile_image($image_url){
    return "<img src='{$image_url}' height='200px' width='200px' />";
}

$trans = array(
    "[[1]]" => "Vishal",
    "[[2]]" => "Kumar",
    "[[3]]" => "Sahu",
    "[[4]]" => "Web Designer",
    "[[5]]" => "Draw and Paint",
    "[[6]]" => ucwords("any programming language"),
    "[[7]]" => strtoupper("PHP, JAVASCRIPT and HTML"),
    "[[8]]" => get_profile_image("http://php.net/images/logos/php-logo.svg"),
    "[[9]]" => "http://php.net/images/logos/php-logo.svg"
    );
$str = <<<HEREDOC_1
[[8]]
<pre>My name is [[1]] [[2]] [[3]].
I am a [[4]] and I love to [[5]].
I don't know [[6]] but I know [[7]] little bit.</pre>
Here is my profile image <img src='[[9]]' alt='[[1]]-[[2]]-[[3]]-[[4]]' />
HEREDOC_1;
echo strtr($str, $trans);

它的输出是

[http://php.net/images/logos/php-logo .svg] 我的名字是维沙尔·库马尔
萨胡。我是一名网页设计师,我喜欢绘画。我不知道
任何编程语言,但我对 PHP、JAVASCRIPT 和 HTML 知之甚少
少量。这是我的个人资料图片 [Vishal-Kumar-Sahu-Web Designer]

它在 5.6 上运行良好。

My bet is PHP's strtr function...

<?php
function get_profile_image($image_url){
    return "<img src='{$image_url}' height='200px' width='200px' />";
}

$trans = array(
    "[[1]]" => "Vishal",
    "[[2]]" => "Kumar",
    "[[3]]" => "Sahu",
    "[[4]]" => "Web Designer",
    "[[5]]" => "Draw and Paint",
    "[[6]]" => ucwords("any programming language"),
    "[[7]]" => strtoupper("PHP, JAVASCRIPT and HTML"),
    "[[8]]" => get_profile_image("http://php.net/images/logos/php-logo.svg"),
    "[[9]]" => "http://php.net/images/logos/php-logo.svg"
    );
$str = <<<HEREDOC_1
[[8]]
<pre>My name is [[1]] [[2]] [[3]].
I am a [[4]] and I love to [[5]].
I don't know [[6]] but I know [[7]] little bit.</pre>
Here is my profile image <img src='[[9]]' alt='[[1]]-[[2]]-[[3]]-[[4]]' />
HEREDOC_1;
echo strtr($str, $trans);

it's output is

[http://php.net/images/logos/php-logo.svg] My name is Vishal Kumar
Sahu. I am a Web Designer and I love to Draw and Paint. I don't know
Any Programming Language but I know PHP, JAVASCRIPT AND HTML little
bit. Here is my profile image [Vishal-Kumar-Sahu-Web Designer]

It is working fine on 5.6.

鹊巢 2024-10-16 16:22:13

我相信正则表达式是:(

/\[\[[1-9]{1,3}\]\]/g

双括号内的 1 到 3 位数字。)

The regex, I believe, would be:

/\[\[[1-9]{1,3}\]\]/g

(for a 1-to-3 digit number inside double brackets.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文