2014-08-28 256 views
0

與特定的類HTML我有這個測試字符串刪除所有的HTML標籤,除了使用正則表達式

@[email protected] <span class="mention">@test</span> @[email protected] <span class="mention">@test</span> [email protected] Test @test.com <br> <a></a> <hr></hr> <span>dsfsfdsdfsdfs asdf </span> <span>test</span> <a>f</a> 

而且我希望能去除所有標籤,同時留下自己的內容只有當階級提跨度。爲了會留下如下:

@[email protected] <span class="mention">@test</span> @[email protected] <span class="mention">@test</span> [email protected] Test @test.com dsfsfdsdfsdfs asdf test f 

這是據我得到了,但它仍然無法正常工作

/(?!<span class="mention".*?<\/span>)(<([a-z]*)>(.[^<>]*|)<(\/[a-z]*)>)/g 

任何幫助將不勝感激!

+2

http://stackoverflow.com/a/1732454/2640017 – 2014-08-28 05:38:36

+2

不要用正則表達式解析HTML。 – 2014-08-28 05:38:51

回答

0

在這裏你去

正則表達式

/(<span(?![^>]*class="mention")[^>]*>)([^<]*)<\/span>/g 

更換模式

\2 

測試字符串

@[email protected] <span class="mention">@test</span> @[email protected] <span class="mention">@test</span> [email protected] Test @test.com <br> <a></a> <hr></hr> <span>dsfsfdsdfsdfs asdf </span> <span>test</span> <a>f</a> 

結果

@[email protected] <span class="mention">@test</span> @[email protected] <span class="mention">@test</span> [email protected] Test @test.com <br> <a></a> <hr></hr> dsfsfdsdfsdfs asdf test <a>f</a> 

演示

嘗試demo here

這將撕掉所有沒有指定的類屬性class="mention"


跨度標籤

編輯

這裏要求的是你可以去掉所有的HTML標籤,除了已經要求一個提一流

正則表達式

/(<(\w+)(?![^>]*class="mention")[^>]*>)([^<]*)<\/\2>|(?:<br>|<br\/>)/g 

更換模式

\3 

結果

@[email protected] <span class="mention">@test</span> @[email protected] <span class="mention">@test</span> [email protected] Test @test.com dsfsfdsdfsdfs asdf test f 

演示

嘗試demo here

+0

謝謝!對不起,我不是最清晰的,但我想刪除所有的HTML標籤不只是跨越! – MichaelH 2014-08-28 06:13:18

+0

感謝您的編輯!但是我想保留實際內容,只需匹配標籤 – MichaelH 2014-08-28 07:08:17

+0

請參閱http://regex101.com/r/gF7wW6/6,如果這是您正在尋找的。或者這個http://regex101.com/r/gF7wW6/7,也刪除了從br標籤中的非捕獲。 – pushpraj 2014-08-28 07:20:50