【问题标题】:Transforming tag with regex replace [closed]使用正则表达式替换转换标签 [关闭]
【发布时间】:2022-01-31 16:08:12
【问题描述】:

我有一个要转换的标签。我正在尝试使用 php 函数执行此操作: 我怎样才能进行这种转变?

content before @[youtube](XIMLoLxmTDw) content after =>  content before <div class="iframe-wrapper"><iframe src="https://www.youtube.com/embed/XIMLoLxmTDw" frameborder="0" allowfullscreen="true"></iframe></div> content after

【问题讨论】:

    标签: php regex replace


    【解决方案1】:
    function getStringBetween($str,$from,$to)
    {
        $sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
        return substr($sub,0,strpos($sub,$to));
    }
    $string='<div class="iframe-wrapper"><iframe src="https://www.youtube.com/embed/XIMLoLxmTDw" frameborder="0" allowfullscreen="true"></iframe></div>';
    $start='embed/';
     $end='"';
    $idYoutube=getStringBetween($string , $start,$end);
    echo $idYoutube;
    

    【讨论】:

    • 确保始终添加一些文本(非代码)信息来解释您的答案为何有效。
    【解决方案2】:

    我不确定我是否理解你,但也许这段代码 sn-p 可以帮助你?

    <?php
    
    $re = '/\@\[youtube\]\((.*)\)/';
    $str = '@[youtube](XIMLoLxmTDw)';
    $subst = '<div class="iframe-wrapper"><iframe src="https://www.youtube.com/embed/$1" frameborder="0" allowfullscreen="true"></iframe></div>';
    
    $result = preg_replace($re, $subst, $str, 1);
    
    echo $result;
    

    Proof of concept on Regex101

    【讨论】:

    • 很酷的方式。谢谢。我将学习正则表达式。对不起这个问题
    • 不用担心。编码愉快。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    相关资源
    最近更新 更多