PHP / MySQL中的短代码/标签

时间:2017-02-25 11:17:07

标签: php mysql

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

[姓名] = John Doe

[email] = johny@gmail.com

[phone] = 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); 

2 个答案:

答案 0 :(得分:0)

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

您也可以使用Ajax jquery form plugin

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

答案 1 :(得分:0)

如果您只想使用数据库或数组中的名称替换[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