使用preg_match_all获取Div id

时间:2016-09-23 06:15:32

标签: php preg-match-all

我有一个如下字符串:

this is a testing string. Below is first div with id.
<div id='divid_first_fN8GiCLO_div'></div>
this is a testing string. Below is second div with id.
<div id='divid_second_fN8GiCLO_div'></div>
this is a testing string. Below is third div with id.
<div id='divid_third_fN8GiCLO_div'></div>

必填结果:

this is a testing string. Below is first div with id.
<iframe src="first_fN8GiCLO.html">
this is a testing string. Below is first div with id.
<iframe src="second_fN8GiCLO.html">
this is a testing string. Below is first div with id.
<iframe src="third_fN8GiCLO.html">

我有div id与我,需要更改iframe源代码,我可以用某种方式使用 preg_match_all 来完成此操作..因为它可以在字符串中的多个位置

我需要选择ID表格div并将该ID放入iframe并删除该div。 谢谢!

1 个答案:

答案 0 :(得分:0)

我建议使用preg_replace_callback

#!/usr/bin/php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);


$in = "this is a testing string. Below is first div with id.
<div id='divid_first_fN8GiCLO_div'></div>
this is a testing string. Below is second div with id.
<div id='divid_second_fN8GiCLO_div'></div>
this is a testing string. Below is third div with id.
<div id='divid_third_fN8GiCLO_div'></div>";

$out = preg_replace_callback('/<div id=.divid_(\w+)_div.><\/div>/',function ($m) {
    return '<iframe src="'.$m[1].'.html">';
},$in);

echo $out;