doukang7501 2014-09-14 16:12
浏览 21
已采纳

通过PHP将自定义脚本标记转换为带有锚标记的新脚本

I need some help with converting a string in PHP. I've been trying to do this for hours but I can only seem to convert simple scripts with str_replace().

I'm trying to convert the custom script below:

<start=0:03>Line one goes here<end=0:09>
<start=0:09>Line two goes here<end=0:12>
<start=0:20>Line three goes here<end=0:26>
<start=0:32>Line four goes here<end=0:42>

Into a new script with anchor tags like this:

<a href="?start=0:03&end=0:09">Line one goes here</a>
<a href="?start=0:09&end=0:12">Line two goes here</a>
<a href="?start=0:20&end=0:26">Line three goes here</a>
<a href="?start=0:32&end=0:42">Line four goes here</a>

Can anyone help please?

Thank you.

  • 写回答

1条回答 默认 最新

  • dorisdong0514 2014-09-14 16:35
    关注

    For this kind of a little elaborate search/replacement, the most handy is to use a regex pattern with preg_replace:

    $re = '/<(start=\d+:\d+)(>.*?<)(end=\d+:\d+)>/s';
    $subst = '<a href="?$1&$3$2/a>';
    $result = preg_replace($re, $subst, $yourstring);
    

    pattern details:

    /                  # pattern delimiter
    <                  # literal <
    (start=\d+:\d+)    # group 1: literal "start=", one or more digits,
                       # literal ":" and one or more digits
    (>.*?<)            # group 2: literal >, all characters until <, that must be followed 
    (end=\d+:\d+>)     # by capture the group 3
    /s                 # pattern delimiter, and s modifier
    

    By default the . matches all characters except the newline character, the s modifier allows it to match newlines too.

    replacement:

    $1, $2, $3 refers to the content captured by the groups

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 表达式必须是可修改的左值
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题