【问题标题】:shortcodes/tags in PHP/MySQLPHP/MySQL 中的简码/标签
【发布时间】:2017-02-25 11:17:06
【问题描述】:

我正在寻找用户可以在 textarea 内容框中添加 [name] 短代码的功能。所以不执行它将用从数据库中获取的数据替换短代码,即John Doe

[姓名] = John Doe

[电子邮件] = johny@gmail.com

[电话] = 9876543210

假设用户输入源代码为<p>my name is [name]</p>

因此提交页面短代码应替换为<p>my name is John Doe</p>

我尝试了下面的代码,但它的短代码很长,打开/关闭和中间的内容很难让客户记住。

$text = "My example text [shortcode_name]content of shortcode[/shortcode_name] is cool.";
$text = "My example text [shortcode_xyz]content of shortcode[/shortcode_name] is cool.";
$bhaku = "ss";

$pattern= '/\[(shortcode_name)\](.|\s)*?\[\/\1\]/'; 
echo preg_replace($pattern,$bhaku ,$text); 

【问题讨论】:

  • 在这种情况下您不需要使用str_replace 吗?也就是说,如果您只想替换 [shortcode] 而不是 [shortcode]Foo bar[/shortcode]

标签: php mysql


【解决方案1】:

您将需要 ajax 从数据库中请求数据而无需重新加载页面。

您也可以使用Ajax jquery form plugin

$('#MyForm').ajaxForm(function(response){
    //Print response
    $('#ResAreaId').html(response);
});

【讨论】:

  • 这是一个 PHP/MySQL 问题,所以我认为这一切都是在服务器端完成的。
【解决方案2】:

如果您只想将[name] 之类的短代码替换为数据库或数组中的名称,则无需使用正则表达式。您可以改为使用 str_replace:

$text = "<p>My name is [name], my phone is [phone] and my email is [email]</p>";        

$db = array('[name]'=>'John Doe', 
            '[email]'=>'johny@gmail.com', 
            '[phone]'=>'9876543210'
            );

echo str_replace(array_keys($db), array_values($db), $text);  

自己试试吧:https://eval.in/742786

如果您在另一种情况下想要替换两个标签之间的输入,您可以使用正则表达式,如下例:

$text = "<p>My name is [name]Jenny[/name], and my phone is [phone]1234567[/phone], and mail: [email]mail@mail.com[/email]</p>";                 

$tags = array('name', 'email', 'phone'); // TAGS TO FETCH INPUT FROM

$input = array(); // ARRAY WITH EXTRACTED INPUT

foreach ($tags as $tag){ // LOOP THROUGH EACH TAG
    $pattern = "/\[$tag ?.*\](.*)\[\/$tag\]/";
    preg_match($pattern, $text, $matches);
    $input[$tag] = isset($matches[1]) ? $matches[1] :''; //GET VALUE IF THE TAG EXISTS IN TEXT, ELSE RETURN EMPTY STRING
}               

print_r($input);

应该给出这个结果:

Array
(
    [name] => Jenny
    [email] => mail@mail.com
    [phone] => 1234567
)

试试看:https://eval.in/742788

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    相关资源
    最近更新 更多