我有一些像这样解析的文本:
一些短信。一些短信。一些短信。一些短信。一些短信。一些短信。一些短信。一些短信。一些短信。一些短信。一些短信。一些短信。一些短信。一些短信。一些短信。一些短信。一些短信。附件=0Winter.jpg/attachmentSome文本。一些短信。一些短信。一些短信。一些短信。一些短信。一些短信。一些短信。一些短信。一些短信。一些短信。一些短信。
我希望匹配并从字符串中删除任何类似于以下文本的实例:
[attachment=0]Winter.jpg[/attachment]其中Winter.jpg可以是任何文本。
不过,我收到了一些PHP通知。我使用regexpal.com来构造它,它在那里工作,但使用Javascript函数:
\[attachment=.*?].*\[/attachment]当我运行这段代码时:
$pm_row['message_text'] = preg_replace('\[attachment=.*?\].*\[/attachment\]', '', $pm_row['message_text']);PHP发出通知抱怨:
[phpBB Debug] PHP Notice: in file /mail_digests.php on line 841: preg_replace() [function.preg-replace]: Delimiter must not be alphanumeric or backslash因此,在类似的代码行中,我用“/”分隔模式:
$post_row['post_text'] = preg_replace('/\[attachment=.*?].*\[/attachment]/', '', $post_row['post_text']);但这会产生以下结果:
[phpBB Debug] PHP Notice: in file /mail_digests.php on line 957: preg_replace() [function.preg-replace]: Unknown modifier 'a'有什么办法解决这个问题吗?
发布于 2010-11-15 19:15:05
你需要转义模式内分隔符的每一次出现。
如果需要在模式中匹配分隔符,则必须使用反斜杠对其进行转义。如果分隔符经常出现在模式中,则选择另一个分隔符以增加可读性是个好主意。
所以逃避吧:
'/\[attachment=.*?].*\[\/attachment]/'
^顺便说一句:目前量词在.*中是贪婪的,这意味着它将尽可能匹配。您可能希望像以前一样使用?将其更改为非贪婪的变量。
发布于 2010-11-15 19:15:41
如果您在表达式中实际使用它(即:在表达式中有一个/ ),那么您需要一个delimeter,如果您在表达式中实际使用它,就需要转义它( [/attachment] )。转义它或更改分隔符(例如#)。
发布于 2010-11-16 21:44:02
我想我能解决这个问题。示例中的测试数据很糟糕,因此我试图匹配无效的模式。
https://stackoverflow.com/questions/4187900
复制相似问题