如何用另一个字符串中的更多字符串替换字符串?

时间:2015-10-26 06:10:52

标签: php regex

我有这段代码:

<body>
    <label id="Label1052">The loop is below</label>
    <img id="Image733" src="logo-2.png">
    <!--the loop--><div id="theLoop">
        <label id="Label736">{title}</label>
        <label id="Label737">{date}</label>
        <label id="Label739">{content}</label>
    </div><!--the loop-->
</body>

预期产出:

<body>
    <label id="Label1052">The loop is below</label>
    <img id="Image733" src="logo-2.png">
    <!--the loop--><div id="theLoop">
        <label id="Label736">Post 1</label>
        <label id="Label737">Jan 1</label>
        <label id="Label739">The content</label>
    </div>
    <div id="theLoop">
        <label id="Label736">Post 2</label>
        <label id="Label737">Jan 5</label>
        <label id="Label739">The content</label>
    </div>
    <div id="theLoop">
        <label id="Label736">Post 3</label>
        <label id="Label737">Jan 6</label>
        <label id="Label739">The content</label>
    </div><!--the loop-->
</body>

这是我的PHP:

// contains the content above
$markup = "<body>...</body>";

// find the loop and get the contents that has tokens
$match = preg_match("<!--the loop-->(.*)<!--the loop-->");

for (var i;i<itemCount;i++) {
    $item = items[i];
    // start to replace content - there are many tokens - I have a function
    $newContent = replaceTokensInContent($item, $match);
    $myArray.push($newContent);
}

$newContent = $myArray.join();

// put the content back into the markup 
$updated_markup = preg_replace("<!--the loop-->(.*)<!--the loop-->", $newContent, $markup);

我想获取两个标记<!--the loop-->之间的内容,然后多次替换标记(我有一个函数)然后再将填充的字符串放回主字符串中。

我知道如何在JavaScript中使用此正则表达式而不是PHP。

1 个答案:

答案 0 :(得分:1)

当您在寻找使用正则表达式的方法时,您可以考虑使用评论中标记的DomDocument方法。

$doc = new DOMDocument();
$doc->loadHTMLFile(...);

$xpath = new DOMXpath($doc);
$loop = $xpath->query("//*[@id='theLoop']")->item(0);

拥有$loop,您现在可以插入,删除或替换节点。看看这个explanation as a starting point