如何使用PHP平衡标签

时间:2009-11-12 20:26:02

标签: php

在下面的字符串中,我想用一些文本<!--more-->替换FOOBAR,然后截断字符串。

<p>The quick <a href="/">brown</a> fox jumps <!--more-->
over the <a href="/">lazy</a> dog.</p>

我已经到了这一步:

<p>The quick <a href="/">brown</a> fox jumps FOOBAR

...但正如您所看到的,<p>标记未关闭。关于如何始终如一地平衡标签的任何想法?我是PHP新手。

我正在使用的数组如下所示:

array(2) {
  [0]=>
  string(50) "<p>The quick <a href="/">brown</a> fox jumps "
  [1]=>
  string(45) " over the <a href="/">lazy</a> dog.</p>"
}

5 个答案:

答案 0 :(得分:4)

您可以使用wordpress force_balance_tags函数。实施工作在这里: -

http://core.trac.wordpress.org/browser/trunk/wp-includes/formatting.php

这是一个独立的功能,您只需复制+粘贴代码即可。

function force_balance_tags( $text ) {

用法很简单

$bad_text = "<div> <p> some text </p> " ;

echo force_balance_tags($ bad_text);

因为这是wordpress的一部分,所以它经过了尝试和测试,并且优于adHoc正则表达式macthing解决方案。

答案 1 :(得分:2)

如果可能的话,我建议将HTML解析为DOM并以这种方式处理它,遍历文本节点,直到找到该字符串,然后截断文本节点并删除任何进一步的节点在那之后(保留父母完整)。然后将DOM重新序列化为HTML。

答案 2 :(得分:1)

我还没有完全测试过这个,但它至少适用于你的例子。假设格式良好的XML。

<?php
$reader = new XMLReader;
$writer = new XMLWriter;

// load the XML string into the XMLReader
$reader->xml('<p>The quick <a href="/">brown</a> fox jumps <!--more--> over the <a href="/">lazy</a> dog.</p>');
// write the new XML to memory
$writer->openMemory();
$done = false;

// XMLReader::read() moves the current read location to the next node
while ( !$done && $reader->read()) {
    // choose action based on the node type
    switch ($reader->nodeType) {
        case XMLReader::ELEMENT:
            // read an element, so write it back to the output
            $writer->startElement($reader->name);
            if ($reader->hasAttributes) {
                // loop through all attributes and write them
                while($reader->moveToNextAttribute()) {
                    $writer->writeAttribute($reader->name, $reader->value);
                }
                // move back to the beginning of the element
                $reader->moveToElement();
            }
            // if the tag is empty, close it now
            if ($reader->isEmptyElement) {
                $writer->endElement();
            }
            break;
        case XMLReader::END_ELEMENT:
            $writer->endElement();
            break;
        case XMLReader::TEXT:
            $writer->text($reader->value);
            break;
        case XMLReader::COMMENT:
            // you  can change this to be more flexible if you need
            // e.g. preg_match, trim, etc.
            if (trim($reader->value) == 'more') {

                // write whatever you want in here. If you have xml text
                // you want to write verbatim, use writeRaw() instead of text()
                $writer->text('FOOBAR');

                // this is where the magic happens -- endDocument closes
                // any remaining open tags
                $writer->endDocument();
                // stop the loop (could use "break 2", but that gets confusing
                $done = true;
            }
            break;
    }
}
echo $writer->outputMemory();

答案 3 :(得分:0)

当你陈述问题时,它就像这样容易:

str_replace('<!--more-->', 'FOOBAR', $original_text);

也许如果你更新你的问题来解释什么有一个数组与整个问题有关将有助于解释正确的问题 - (字符串<!--more-->应该在数组中?)

答案 4 :(得分:0)

您必须在占位符文本之前找到已打开但未关闭的所有标记。 像现在一样插入新文本,然后关闭标签。

这是一个草率的例子。我认为这段代码适用于所有有效的HTML,但我并不积极。它肯定会接受无效的标记。但无论如何:

$h = '<p>The quick <a href="/">brown</a> fox jumps <!--more-->
over the <a href="/">lazy</a> dog.</p>';

$parts = explode("<!--more-->", $h, 2);
$front = $parts[0];

/* Find all opened tags in the front string */
$tags = array();
preg_match_all("|<([a-z][\w]*)(?: +\w*=\"[\\w/%&=]+\")*>|i", $front, $tags, PREG_OFFSET_CAPTURE);
array_shift($tags); /* get rid of the complete match from preg_match_all */

/* Check if the opened arrays have been closed in the front string */
$unclosed = array();
foreach($tags as $t) {
    list($tag, $pos) = $t[0];
    if(strpos($front, "</".$tag, $pos) == false) {
        $unclosed[] = $tag;
    }
}    

/* Print the start, the replacement, and then close any open tags. */
echo $front;
echo "FOOBAR";
foreach($unclosed as $tag) {
    echo "</".$tag.">";
}

输出

<p>The quick <a href="/">brown</a> fox jumps FOOBAR</p>