【问题标题】:How to replace a string with more strings in another string?如何用另一个字符串中的更多字符串替换一个字符串?
【发布时间】:2015-10-26 06:10:51
【问题描述】:

我有这个代码:

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

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

我知道如何在 JavaScript 但不知道 PHP 中执行此正则表达式。

【问题讨论】:

  • 能否请您尝试放置您正在寻找的最终输出。
  • 你可能的预期输出是什么。 Regex is not perfect tool to work along with HTML
  • 叶氏家族和Sashant的@Uchiha,我刚刚更新了问题。我将添加我的预期输出。
  • preg_match($needle, $haystack), preg_replace($pattern, $replacement, $haystack)。现在检查您的使用情况...
  • 为什么不用一个好的parser/DomDocument来完成这个任务?

标签: php regex


【解决方案1】:

当您正在寻找一种使用正则表达式的方法时,您不妨考虑使用 cmets 中标记的 DomDocument 方法。

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

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

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

【讨论】:

    猜你喜欢
    • 2013-12-03
    • 2021-06-15
    • 2019-05-14
    • 1970-01-01
    • 2017-01-28
    • 2017-03-07
    • 2011-04-06
    • 2021-12-04
    相关资源
    最近更新 更多