douciwang6819 2014-06-17 00:20
浏览 53
已采纳

正则表达式PHP如何匹配字符串的内部部分[重复]

This question already has an answer here:

I need a php regex that will do the following with my original string

<div>The quick jumped over <p>[video=xdf890sfadf]</p> the white fence.</div>

to

<div>The quick jumped over <p><iframe src="http://www.youtube.com/embed/xdf890sfadf?rel=0&amp;vq=hd720" height="365" width="650" allowfullscreen="" frameborder="0"></iframe></p> the white fence.</div>

So what I need do to is pull the video ID out of the any give string of html.

I want to use the preg_replace() function for this, but I'm confused about the proper regex to use with it. Please help.

</div>
  • 写回答

1条回答 默认 最新

  • dongwuwan5646 2014-06-17 00:25
    关注

    A simple search here on SO and should be no problem. Just get it using preg_match(). Consider this example:

    $original_string = '<div>The quick jumped over <p>[video=xdf890sfadf]</p> the white fence.</div>';
    preg_match('/\[video=([^\]]+)\]/', $original_string, $matches);
    if(!empty($matches)) {
        $value = $matches[1];
        $video = $matches[0];
        $new_string = '<div>The quick jumped over <p><iframe src="http://www.youtube.com/embed/'.$value.'?rel=0&amp;vq=hd720" height="365" width="650" allowfullscreen="" frameborder="0"></iframe></p> the white fence.</div>';
        echo $new_string;
    }
    

    Note: credit goes to https://stackoverflow.com/a/8935740/1978142

    Sample Output

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

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题