2
2
2slide2014-02-22 02:16:34
PHP
2slide, 2014-02-22 02:16:34

What is the regular expression for replacing the code tag with pre code?

In the example, the code tag is replaced by src.
there is a task to find all < src > ... < /src > tags
and enclose in < pre> < src class=''> ... < /src >< /pre>
the src tag can have the lang attribute of the
regular expression

$sText = preg_replace("/<src * lang=(.*?)>(.*)<\/src\>/is", "<pre><src class=$1>$2</src></pre>", $sText);

Works with one block < src > ... < /src > does < pre>< src class=''>..< /src>< /pre>
with several blocks does like this
< pre >
< src src class='' > ... < /src >
< src src class=''> ... < /src >
< /pre>
And you need this
< pre >
< src src class='' > ... < /src >
< /pre >
< pre >
< src src class=''> ... < /src >
< /pre>
I couldn't solve the problem myself. Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
DeFacto, 2014-02-22
@2slide

$sText = preg_replace("#^<src lang=(.*?)>(.*?)</src>$#ism", "<pre><src class=$1>$2</src></pre>", $sText);

E
egor_nullptr, 2014-02-22
@egor_nullptr

There are wonderful classes for working with XML, and there is no need to torture regular expressions.

$doc = new DomDocument('1.0', 'utf-8');
$doc->loadXml($text);
$xp = new DomXPath($doc);

foreach ($xp->query('//src') as $src_node) {
    $pre_node = $doc->createElement('pre');
    $pre_node->appendChild($src_node);
    $src_node->parentNode->replaceChild($pre_node, $src_node);
};

$new_text = $doc->saveXML();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question