2015-10-26 22 views
2

我有這樣的代碼:如何用另一個字符串中的更多字符串替換字符串?

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

+0

你可以請嘗試把你正在尋找的最終輸出。 –

+2

什麼是您可能的預期輸出。 [正則表達式不是完美的工具,與HTML一起工作](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) –

+0

@葉奇從葉氏族和Sashant,我剛剛更新了這個問題。我會添加我的預期輸出。 –

回答

1

當您在尋找具有正則表達式的方法時,不妨考慮使用在註釋中標記爲DomDocument的方法。

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

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

具有$loop,你現在可以插入,刪除或替換的節點。看看這個explanation as a starting point

相關問題