Trying to get my head around how to create a PHP preg replace for a string that will convert

<div class="active make_link">1</div>
<div class="make_link digit"><a href="">2</a></div>
<div class="make_link digit"><a href="">3</a></div>
etc

to

<li class="active">1</li>
<li><a href="">2</a></li>
<li><a href="">3</a></li>
etc

Figured out how to replace the elements but not how to keep the class active.

$new_pagination = preg_replace('/<div[^>]*>(.*)<\/div>/U', '<li>$1</li>', $old_pagination);

Any ideas?

有帮助吗?

解决方案

Try this..You can do this using str_ireplace too

<?php
$html='<div class="active make_link">1</div>
<div class="make_link digit"><a href="">2</a></div>
<div class="make_link digit"><a href="">3</a></div>';

echo str_ireplace(array('<div','</div','class="active make_link"','class="make_link digit"'),array('<li','</li','active',''),$html);

其他提示

Or simple html dom:

require_once('simple_html_dom.php');

$doc = str_get_html($string);
foreach($doc->find('div') as $div){
  $div->tag = 'li';
  preg_match('/active/', $div->class, $m);
  $div->class = @$m[0];
}

echo $doc;

This may seem a bit excessive, but it's a good use-case for XSLT:

$xslt = <<<XML
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="@*|node()">
    <xsl:copy><xsl:apply-templates select="@*|node()" /></xsl:copy>
  </xsl:template>
  <xsl:template match="div">
    <li>
      <xsl:if test="@*[name()='class' and contains(., 'active')]">
        <xsl:attribute name="class">active</xsl:attribute>
      </xsl:if>
      <xsl:apply-templates select="node()" />
    </li>
  </xsl:template>
</xsl:stylesheet>
XML;

It uses the identity rule and then overrides handling for <div>, adding a class="active" for nodes that have such a class name.

$xsl = new XSLTProcessor;

$doc = new DOMDocument;
$doc->loadXML($xslt);

$xsl->importStyleSheet($doc);

$doc = new DOMDocument;
$html = <<<HTML
<div class="active make_link">1</div>
<div class="make_link digit"><a href="">2</a><div>test</div></div>
<div class="make_link digit"><a href="">3</a></div>
HTML;

$doc->loadHTML($html);

echo $xsl->transformToDoc($doc)->saveHTML();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top