duanoucuo7045 2010-01-29 10:59
浏览 21
已采纳

字符串解析帮助

I have a paragraph of text in the following format:

  text text text <age>23</age>. text text <hobbies>...</hobbies>

I want to be able to

1) Extract the text found between each <age> and <hobbies> tag found in the string. So for example, I would have an array called $ages which will contain all ages found between all the <age></age> tags, and then another array $hobbies which will have the text between the <hobbies></hobbies> tags found throughout the string.

2) Be able to replace the tags which are extracted with a marker, such as {age_444}, so e.g the above text would become

  text text text {age_444}. text text {hobbies_555}

How can this be done?

  • 写回答

3条回答 默认 最新

  • dongliu1883 2010-01-29 11:15
    关注
    //Extract the age
    preg_match_all("#<age>(.*?)</age>#",$string,$match);
    $ages=$match[1];
    //Extract the hobby
    preg_match_all("#<hobbies>(.*?)</hobbies>#",$string,$match);
    $hobbies=$match[1];
    
    //Replace the age
    $agefn=create_function('$match','$query=mysql_query("select ageid...where age=".$match[1]); return "<age>{age_".mysql_fetch_object($query)->ageid."}</age>"');
    $string=preg_replace_callback("#<age>(.*?)</age>#",$agefn,$string);
    
    //Replace the hobby
    $hobfn=create_function('$match','$query=mysql_query("select hobid...where hobby=".$match[1]); return "<hobbies>{hobbies_".mysql_fetch_object($query)->hobid."}</hobbies>"');
    $string=preg_replace_callback("#<hobbies>(.*?)</hobbies>#",$hobfn,$string);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: