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

时间:2022-02-14 20:11:58

I have this code:

我有这个代码:

<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>

Expected output:

预期产量:

<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>

Here is my PHP:

这是我的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);

I want to get the contents between both tokens <!--the loop--> and then replace tokens in that multiple times (I have a function) and then put that populated string back into the main string again.

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

I know how to do this regex in JavaScript but not PHP.

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

1 个解决方案

#1


1  

While you were looking for a way with regular expressions, you might as well consider using a DomDocument approach as marked in the comments.

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

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

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

Having the $loop, you can now insert, delete or replace nodes. Have a look at this explanation as a starting point.

拥有$循环,您现在可以插入,删除或替换节点。以这个解释为出发点。

#1


1  

While you were looking for a way with regular expressions, you might as well consider using a DomDocument approach as marked in the comments.

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

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

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

Having the $loop, you can now insert, delete or replace nodes. Have a look at this explanation as a starting point.

拥有$循环,您现在可以插入,删除或替换节点。以这个解释为出发点。