【发布时间】:2015-02-21 17:23:26
【问题描述】:
问题来了:
我有两个 div #post-playlist-list 和 post-playlist-description
我想使用两个简码 [texte-article] 和 [playlist-article]
我需要一个函数,将 [texte-article][/texte-article] 之间的所有内容放入#post-playlist-list
以及另一个将 [playlist-article][/playlist-article] 内容放入#post-playlist-description 的函数
我开始在 preg_replace 学习,但语法不是那么容易学习。
如果你能帮我解决这个问题,那就太好了。
好的,我尝试了没有错误但似乎没有返回任何内容的函数 我不需要逃避正则表达式的第二个] 离子吗?比如“/[texte-article](.*)[/texte-article]/”
这是我的 single.php 中的代码:
<div id="post-playlist-list" class="box">
<?php
$id = get_the_ID();
$post = get_post($id);
$content = apply_filters('the_content', $post->post_content);
$content = str_replace( ']]>', ']]>', $content );
echo $content;
?>
</div>
<div id="post-playlist-description" >
<?php
echo $content;
?>
</div>
这是我的 single.php 中的代码:
function texte_article_function() {
preg_replace_callback("/\[texte-article\](.*)\[\/texte-article\]/", function($matches) {
//$matches contains an array of all matches
//$matches[0] stores the full pattern match: \[texte-article](.*)\[\/texte-article]
//$matches[1] stores the first subpattern match: (.*)
//Do whatever text parsing you need to do here and return the result.
$content = $matches[0];
return $content;
}, $postdata);
}
function playlist_article_function() {
preg_replace_callback("/\[playlist-article\](.*)\[\/playlist-article\]/", function($matches) {
//$matches contains an array of all matches
//$matches[0] stores the full pattern match: \[texte-article](.*)\[\/texte-article]
//$matches[1] stores the first subpattern match: (.*)
//Do whatever text parsing you need to do here and return the result.
$content = $matches[0];
return $content;
}, $postdata);
}
function register_shortcodes(){
add_shortcode('texte-article', 'texte_article_function');
add_shortcode('playlist-article', 'playlist_article_function');
}
add_action( 'init', 'register_shortcodes');
【问题讨论】:
-
您不需要 preg_replace 。您是否尝试在模板中插入文本?如果是这样,为什么不直接插入文本而不是用短代码包围它?如果您不尝试在模板中插入,那么这两个 div 在哪里?
-
是的,我当时就想到了。更容易实现,但我想使用正则表达式和简码来避免用户必须输入代码。然后使用简码我可以使用 tinymce 创建简码按钮。感谢您的回答