Regular expression - PHP regular replacement problem

WBOY
Release: 2016-09-27 14:18:07
Original
1090 people have browsed it

俺的正则比较菜,现在有个正则替换的问题一直搞不定,需求是这样的:

一些内容里的标签

<code><p style="dsfdsf">(这里有任意内容和标签)<img class="sdfdsf" src="tupian.jpg">( 这里也有任意内容和标签)</p>
</code>
Copy after login
Copy after login

然后项替换成这样:

<code><p style="dsfdsf">(这里有任意内容和标签)( 这里也有任意内容和标签)</p><figure><img src="tupian.jpg" /></figure>
</code>
Copy after login
Copy after login

简单说就是img外面包上figure然后抽出来放到P后面,然后用preg_replace该怎么写呢?

回复内容:

俺的正则比较菜,现在有个正则替换的问题一直搞不定,需求是这样的:

一些内容里的标签

<code><p style="dsfdsf">(这里有任意内容和标签)<img class="sdfdsf" src="tupian.jpg">( 这里也有任意内容和标签)</p>
</code>
Copy after login
Copy after login

然后项替换成这样:

<code><p style="dsfdsf">(这里有任意内容和标签)( 这里也有任意内容和标签)</p><figure><img src="tupian.jpg" /></figure>
</code>
Copy after login
Copy after login

简单说就是img外面包上figure然后抽出来放到P后面,然后用preg_replace该怎么写呢?

我可否理解为,

  • 提取p下面的所有img标签到p外,如果是多个img,这个需要使用preg_match才行

  • 并且p里面会有其他标签,除了p标签外

如果里面只有一个img

<code>//正则
$p = '#<p(?<p>.*?)>(?<text1>.*?)(?<img>\<img.*?>)(?<text2>.*?)</p>#i';
//替换
$r = '<p$1>$2$4</p><figure>$3</figure>';
//原内容
$s = '<p class="asas">fsdfsdfsf<img src="" >kolja;<span>a</span>d;lasd</p>';

echo preg_replace($p, $r, $s);

// 结果:
// <p class="asas">fsdfsdfsfkolja;<span>a</span>d;lasd</p><figure><img src="" ></figure></code>
Copy after login

有多个img

<code>$s = '<p class="asas">fsdfsdfsf<img src="1" />kolja;<span>a<img src="2" ></span>d;lasd</p>asdaa<p><img src="3"></p>';

echo preg_replace_callback('#<p(?<p>.*?)>(?<text>.*?)</p>#', function($matches) {
    preg_match_all('#<img.*?>#', $str = $matches[0], $matches1, PREG_OFFSET_CAPTURE );
    foreach (array_reverse($matches1[0]) as $v)
        $str = substr_replace($str, '', $v[1], strlen($v[0]));
    return $str.'<figure>'.implode('',array_map(function($v){return $v[0];}, $matches1[0])).'</figure>';
}, $s);

// 结果:
// <p class="asas">fsdfsdfsfkolja;<span>a</span>d;lasd</p><figure><img src="1" /><img src="2" ></figure>asdaa<p></p><figure><img src="3"></figure></code>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template