PHP替换子标签,在字符串

时间:2017-12-26 18:03:45

标签: php preg-replace

我需要更换虚拟标签,客户可以为每个虚拟标签添加标签

<?php
    $mycontent  = 'Test of text <<[with user-filled separator label: ]my_tag]>> and <<[Another delimiter ]my_tag2]>> and <<my_tag3>>';

    $replace_my_tag     = 'ab ab ab ab ab ab';
    $replace_my_tag2    = 'cd cd cd cd cd cd';
    $replace_my_tag3    = 'ef ef ef ef ef ef';

    //REPLACE MY TAG    
    //how to make this regular expression
    echo preg_replace('', '', $mycontent);

    //i want results (case exists $replace value)
    //Test of text with user-filled separator label: ab ab ab ab ab ab and <<[Another delimiter ]my_tag2]>> and <<my_tag3>>

    //REPLACE MY TAG 2  
    //how to make this regular expression
    echo preg_replace('', '', $mycontent);

    //i want results (case exists $replace value)
    //Test of text with user-filled separator label: ab ab ab ab ab ab and Another delimiter cd cd cd cd cd cd and <<my_tag3>>


    //REPLACE MY TAG 3  
    //how to make this regular expression
    echo preg_replace('', '', $mycontent);

    //i want results (case exists $replace value)
    //Test of text with user-filled separator label: ab ab ab ab ab ab and Another delimiter cd cd cd cd cd cd and ef ef ef ef ef ef end

?>

您需要创建一个可以轻松替换标签的正则表达式 问候 马可

2 个答案:

答案 0 :(得分:0)

$mycontent  = 'Test of text <<[with label: ]my_tag]>> end.';
$replace    = 'ab ab ab ab ab ab';
 echo str_replace('my_tag', $replace,  $mycontent);

答案 1 :(得分:0)

不是100%我理解确切的目标,所以根据我对这个问题的解释,我认为这可能就是答案。

我的理解是,如果$ replace变量存在,您想要删除尖括号和方括号,然后将'my_tag'替换为$ replace的内容。我为此使用了preg_replace(),并将$ replace变量插入到字符串中。

但如果没有$ replace变量,那么我只使用str_replace(),因为它更快,内容中不需要整个部分。

#include <gst/gst.h>
int main(int argc, char *argv[]) {
GstElement *pipeline;
GstBus *bus;
GstMessage *msg;

/* Initialize GStreamer */
gst_init (&argc, &argv);

/* Build the pipeline */
pipeline = gst_parse_launch ("playbin uri=https://www.freedesktop.org/software/gstreamer-sdk/data/media/sintel_trailer-480p.webm", NULL);

/* Start playing */
gst_element_set_state (pipeline, GST_STATE_PLAYING);

/* Wait until error or EOS */
bus = gst_element_get_bus (pipeline);
msg = gst_bus_timed_pop_filtered (bus, GST_CLOCK_TIME_NONE, GST_MESSAGE_ERROR | GST_MESSAGE_EOS);

/* Free resources */
if (msg != NULL)
  gst_message_unref (msg);
gst_object_unref (bus);
gst_element_set_state (pipeline, GST_STATE_NULL);
gst_object_unref (pipeline);
return 0;
}

如果案例是$ replace将始终存在,但是条件是否为空,那么我会将isset()函数替换为!empty()。这将根据$ replace的内容进行评估。