1

我想用正则表达式分割一个字符串,然后在我找到匹配项的地方创建一个 dom 元素,然后一直这样做直到字符串结束。给定一个字符串;

$str="hi there! [1], how are you? [2]";

期望的结果:

<sentence>
hi there! <child1>1</child1>, how are you? <child2>2</child2>
</sentence>

我在用php dom -> $dom = new DOMDocument('1.0'); ...

创建根;(这可能没有任何关系,但有些人抱怨不努力和东西..)

        $root= $dom->createElement('sentence', null);
        $root= $dom->appendChild($root);
        $root->setAttribute('attr-1', 'value-1');

我使用了几种方法,例如,有些使用preg-split;

$counter=1;
$pos = preg_match('/\[([1-9][0-9]*)\]/', $str);
    if ($pos == true) {
    $substr=$dom->createElement('child', $counter);
    $root->appendChild($substr);
    $counter++;
    }

我知道代码不值得,但再次表明它不是一种享受。

任何帮助表示赞赏..

4

2 回答 2

3

您的原始代码并没有那么远。但是,您需要使正则表达式以及要添加的文本匹配(并且您需要一个 textnode )。每次匹配后,您还需要推进偏移量,继续匹配的位置:

$str = "hi there! [1], how are you? [2]";

$dom = new DOMDocument('1.0');
$root= $dom->createElement('sentence', null);
$root= $dom->appendChild($root);
$root->setAttribute('attr-1', 'value-1'); # ...

$counter = 0;
$offset = 0;
while ($pos = preg_match('/(.*?)\[([1-9][0-9]*)\]/', $str, $matches, NULL, $offset)) {
    list(, $text, $number) = $matches;
    if (strlen($text)) {
        $root->appendChild($dom->createTextNode($text));
    }
    if (strlen($number)) {
        $counter++;
        $root->appendChild($dom->createElement("child$counter", $number));

    }
    $offset += strlen($matches[0]);
}

while循环与if您的循环相当,只是将其变成一个循环。如果有一些文本匹配,也会添加文本节点(例如,您的字符串中可能有 [1][2] ,因此文本将为空。此示例的输出:

<?xml version="1.0"?>
<sentence attr-1="value-1">
  hi there! <child1>1</child1>, how are you? <child2>2</child2>
</sentence>

编辑在玩了一点之后,我得出的结论是你可能想要划分问题。一部分是解析字符串,另一部分是实际插入节点(例如 textnode 上的 textnode 和 elementnode 如果它是数字)。从后面开始,这立即看起来很实用,首先是第二部分:

$dom = new DOMDocument('1.0');
$root = $dom->createElement('sentence', null);
$root = $dom->appendChild($root);
$root->setAttribute('attr-1', 'value-1'); # ...

$str = "hi there! [1], how are you? [2] test";

$it = new Tokenizer($str);
$counter = 0;
foreach ($it as $type => $string) {
    switch ($type) {
        case Tokenizer::TEXT:
            $root->appendChild($dom->createTextNode($string));
            break;

        case Tokenizer::NUMBER:
            $counter++;
            $root->appendChild($dom->createElement("child$counter", $string));
            break;

        default:
            throw new Exception(sprintf('Invalid type %s.', $type));
    }
}

echo $dom->saveXML();

在这个例子中,我们根本不关心解析。我们要么得到一个文本或一个数字($type),我们可以决定插入文本节点或元素。因此,无论字符串的解析完成,此代码将始终有效。如果它有问题(例如$counter不再有趣),它与字符串的解析/标记化无关。

解析本身已被封装到被Iterator调用的Tokenizer. 它包含将字符串分解为文本和数字元素的所有内容。它处理所有细节,例如如果在最后一个数字之后有一些文本会发生什么等等:

class Tokenizer implements Iterator
{
    const TEXT = 1;
    const NUMBER = 2;
    private $offset;
    private $string;
    private $fetched;

    public function __construct($string)
    {
        $this->string = $string;
    }

    public function rewind()
    {
        $this->offset = 0;
        $this->fetch();
    }

    private function fetch()
    {
        if ($this->offset >= strlen($this->string)) {
            return;
        }
        $result = preg_match('/\[([1-9][0-9]*)\]/', $this->string, $matches, PREG_OFFSET_CAPTURE, $this->offset);
        if (!$result) {
            $this->fetched[] = array(self::TEXT, substr($this->string, $this->offset));
            $this->offset = strlen($this->string);
            return;
        }
        $pos = $matches[0][1];
        if ($pos != $this->offset) {
            $this->fetched[] = array(self::TEXT, substr($this->string, $this->offset, $pos - $this->offset));
        }
        $this->fetched[] = array(self::NUMBER, $matches[1][0]);
        $this->offset = $pos + strlen($matches[0][0]);
    }

    public function current()
    {
        list(, $current) = current($this->fetched);
        return $current;
    }

    public function key()
    {
        list($key) = current($this->fetched);
        return $key;
    }

    public function next()
    {
        array_shift($this->fetched);
        if (!$this->fetched) $this->fetch();
    }

    public function valid()
    {
        return (bool)$this->fetched;
    }
}

这样做将这两个问题分开了。也可以创建一个数组数组或类似的数组来代替迭代器类,但我发现迭代器更有用,所以我很快写了一个。

同样,此示例在最后输出 XML,因此这里是示例性的。请注意,我在最后一个元素之后添加了一些文本:

<?xml version="1.0"?>
<sentence attr-1="value-1">
  hi there! <child1>1</child1>, how are you? <child2>2</child2> test
</sentence>
于 2012-03-19T15:44:16.307 回答
-1

先用正则表达式替换,再解析文档。

$xml = preg_replace('/\[(\d+)\]/', '<child$1>$1</child$1>', $str);
$doc = new DOMDocument('1.0');
$doc->loadXML("<sentence>$xml</sentence>");

这是一个演示。

于 2012-03-19T15:29:16.470 回答