dsklzerpx64815631 2009-11-29 17:01 采纳率: 100%
浏览 79
已采纳

PHP中的通配符替换

I have no experience using regular expressions in PHP, so I usually write some convoluted function using a series of str_replace(), substr(), strpos(), strstr() etc (you get the idea).

This time I want to do this correctly, I know I need to use a regex for this, but am confused as to what to use (ereg or preg), and how exactly the syntax should be.

NOTE: I am NOT parsing HTML, or XML, and sometimes I will be using delimiters other than (for example, | or ~ or [tag] or ::). I am looking for a generic way to do a wildcard replace in between two known delimiters using regex, I am not building an HTML or XML parser.

What I need is a regex that replaces this:

<sometag>everything in here</sometag>

with this:

<sometag>new contents</sometag>

I have read the documentation online for a bit, but I am confused, and am hoping one of you regex experts can pop in a simple solution. I suspect I will pass the values to a function, something like this:

$new_text = swapText ( "<sometag>", $the_new_text_to_go_into_the_dag );

function swapText ( $in_tag_with_brackets_to_update, $in_new_text ) {
 // define tags
 $starting_tag  = $in_tag_with_brackets_to_update;
 $ending_tag    = str_replace( "<", "</", $in_tag_with_brackets_to_update) );

 // not sure if this is the proper regex match string or not
 // and/or if any escaping needs to be done on the tags
 $find_string         = "{$starting_tag}.*{$ending_tag}";
 $replace_with_string = "{$starting_tag}{$in_new_text}{$ending_tag}";

 // after some regex, this function should return new version of <tag>data</tag>
}

Thanks.

  • 写回答

4条回答 默认 最新

  • doucong6884 2009-11-30 00:22
    关注

    @OP, there's no need to use complicated regex or a parser if your task is very simple. an example just using your normal substrings....

    $mystr='<sometag>everything in here</sometag>';
    $start=strpos($mystr,"<sometag>");
    $end=strpos($mystr,"</sometag>");
    print substr($mystr,0,$start+strlen("<sometag>") ) . "new value" . substr($mystr,$end);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法