2014-08-28 258 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