2014-12-19 51 views
-1

我需要幫助編寫一個將內容從標題標記移動到內容標記的正則表達式。正則表達式 - 將內容從標記A移動到標記B

此:

<xml> 
<item> 
    <title>Title 1</title> 
    <content>Text 1</content> 
</item> 
<item> 
    <title>Title 2</title> 
    <content>Text 2</content> 
</item> 
</xml> 

要這樣:

<xml> 
<item> 
    <title>Title 1</title> 
    <content>Title 1 Text 1</content> 
</item> 
<item> 
    <title>Title 2</title> 
    <content>Title 2 Text 2</content> 
</item> 
</xml> 

編輯:我做了一個新的話題,我的問題的一個更好的解釋:Regular expression - moving content between XML tags

SORRY!通過

$1$2 $3 

觀看演示

+0

是否需要是基於正則表達式的解決方案? – 2014-12-19 10:16:12

+0

[不要使用正則表達式解析XML](http://stackoverflow.com/a/1732454/695343) – 2014-12-19 10:28:00

+0

請勿複製您自己的問題。相反,編輯原來的一個。 - 我現在已經關閉了原來的問題,因爲我已經關閉了重複的問題。你應該在你的問題中更清楚你已經嘗試了什麼,所以更確切地說明你確實有問題的部分。顯示你自己的代碼確實有助於在你的問題中更加清晰。 – hakre 2014-12-19 14:27:40

回答

0
(<title>((?:(?!<\/title>).)*)<\/title>\s*<content>)((?:(?!<\/content>).)*) 

嘗試this.Replace。

https://regex101.com/r/vN3sH3/22

$re = "/(<title>((?:(?!<\\/title>).)*)<\\/title>\\s*<content>)((?:(?!<\\/content>).)*)/"; 
$str = "<xml>\n <item>\n <title>Title 1</title>\n <content>Text 1</content>\n </item>\n <item>\n <title>Title 2</title>\n <content>Text 2</content>\n </item>\n</xml>"; 
$subst = "$1$2 $3"; 

$result = preg_replace($re, $subst, $str); 
+0

我不知道如何在preg_replace()中使用你的正則表達式,你能幫我一下嗎? – Dylan 2014-12-19 10:58:17

+0

@Dylan我給了完整代碼 – vks 2014-12-19 11:04:02

+0

它不適合我。這裏是XML文件:http://bit.ly/1C7NZNv – Dylan 2014-12-19 11:49:53

0

首先,使用正則表達式解析domnodes是壞的,也有DOM的解析器,有助於更好。 表達式匹配的標題標籤內容:

正則表達式用最少的標誌(非貪婪,不匹配換行符):否則

\<title\>(.*)\</title\> 

正則表達式:

\<title\>([^\</title\>]*)\</title\> 
0

使用DOTALL修改s做出點在你的正則表達式中也可以匹配換行符。

正則表達式:

~(<title>([^<>]*)<\/title>.*?<content>)~s 

替換字符串:

\1\2 

DEMO

$re = "/(<title>([^<>]*)<\\/title>.*?<content>)/s"; 
$str = "<xml>\n <item>\n <title>Title 1</title>\n <content>Text 1</content>\n </item>\n <item>\n <title>Title 2</title>\n <content>Text 2</content>\n </item>\n</xml>"; 
$subst = "\1\2 "; 
$result = preg_replace($re, $subst, $str);