【发布时间】: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);
我想获取两个标记 <!--the loop--> 之间的内容,然后多次替换标记(我有一个函数),然后再次将填充的字符串放回主字符串。
我知道如何在 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来完成这个任务?