2010-11-10 20 views
2

我有以下字符串:正则表达式选择比我更想(PHP)

blah blah yo<desc>some text with description - unwanted 
text</desc>um hey now some words yah<desc>some other description text 
stuff - more unwanted here</desc>random word and ; things. Now a hyphen 
outside of desc tag - with other text<desc>yet another description - unwanted 
<desc>and that's about it. 

(注意:在现实中有字符串中没有换行/回车我只加了他们这里阅读)

我想从连字符仅选择递减标签的文字前方,也包括前面的空间,也包括结束递减标签。这很简单,因为我只是这样做:

\ s - 。*? < \ /递减>

现在的问题是,这是递减的标签外的连字符是越来越选得过。所以我所有的选择如下:

- unwanted text</desc> 
- more unwanted here</desc> 
- with other text<desc>yet another description - unwanted</desc> 

所以前两个是完美的,但看到最后一行是如何搞砸因为 - 在递减标签外?

仅供参考,如果有兴趣,在我的代码,我做了替换这样的:

$text = preg_replace('/\s-.*?<\/desc>/', '</desc>', $text); 

我试着做一些回顾后的东西,但无法得到它的工作。

任何想法?

谢谢! 马克

回答

1

你可以尝试[^-<>]*,而不是.*?。这限制了正则表达式可以选择的内容,并有效地将尖括号和连字符视为记号。

+0

你的意思是'[^ - <>] *',对吧? – 2010-11-10 17:23:56

+0

@Tim:是的。我将使用-nodeadkeys从此.. – mario 2010-11-10 17:25:02

+0

哇!这很好。我是否会过多地解释这种改变是如何工作的?谢谢! – user390480 2010-11-10 17:31:00

1

如果说明是可以出现在该块只有标签,你可以使用一个可怕的黑客就像这样:

$text = preg_replace('/\s-[^<]*?<\/desc>/', '</desc>', $text); 

但是,如果这需要防弹,你不能用正则表达式来可靠地做到这一点。您可以尝试使用XML解析器并处理结果DOM。