Heim  >  Artikel  >  Backend-Entwicklung  >  正则表达式 - PHP 正则替换的问题

正则表达式 - PHP 正则替换的问题

WBOY
WBOYOriginal
2016-09-27 14:18:071066Durchsuche

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

一些内容里的标签

<code><p style="dsfdsf">(这里有任意内容和标签)<img  class="sdfdsf" src="tupian.jpg" alt="正则表达式 - PHP 正则替换的问题" >( 这里也有任意内容和标签)</p>
</code>

然后项替换成这样:

<code><p style="dsfdsf">(这里有任意内容和标签)( 这里也有任意内容和标签)</p>
<figure><img  src="tupian.jpg" alt="正则表达式 - PHP 正则替换的问题" ></figure>
</code>

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

回复内容:

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

一些内容里的标签

<code><p style="dsfdsf">(这里有任意内容和标签)<img  class="sdfdsf" src="tupian.jpg" alt="正则表达式 - PHP 正则替换的问题" >( 这里也有任意内容和标签)</p>
</code>

然后项替换成这样:

<code><p style="dsfdsf">(这里有任意内容和标签)( 这里也有任意内容和标签)</p>
<figure><img  src="tupian.jpg" alt="正则表达式 - PHP 正则替换的问题" ></figure>
</code>

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

我可否理解为,

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

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

如果里面只有一个img

<code>//正则
$p = '#<p>.*?)>(?<text1>.*?)(?<img  alt="正则表达式 - PHP 正则替换的问题" >\<img . alt="正则表达式 - PHP 正则替换的问题" >)(?<text2>.*?)</text2></img.></text1></p>#i';
//替换
$r = '<p>$2$4</p>
<figure>$3</figure>';
//原内容
$s = '<p class="asas">fsdfsdfsf<img  src="" alt="正则表达式 - PHP 正则替换的问题" >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="" alt="正则表达式 - PHP 正则替换的问题" ></figure></code>

有多个img

<code>$s = '<p class="asas">fsdfsdfsf<img  src="1" alt="正则表达式 - PHP 正则替换的问题" >kolja;<span>a<img  src="2" alt="正则表达式 - PHP 正则替换的问题" ></span>d;lasd</p>asdaa<p><img  src="3" alt="正则表达式 - PHP 正则替换的问题" ></p>';

echo preg_replace_callback('#<p>.*?)>(?<text>.*?)</text></p>#', function($matches) {
    preg_match_all('#<img . alt="正则表达式 - PHP 正则替换的问题" >#', $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" alt="正则表达式 - PHP 正则替换的问题" ><img  src="2" alt="正则表达式 - PHP 正则替换的问题" ></figure>asdaa<p></p>
<figure><img  src="3" alt="正则表达式 - PHP 正则替换的问题" ></figure></img.></code>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:PHP 快速排序法的问题Nächster Artikel:linux 下php命令行模式