开发者

PHP and preg_replace

I have some text I am parsing like this:

Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. [attachment=0开发者_运维知识库]Winter.jpg[/attachment]Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text.

I want to match and remove any instance of text like this from the string:

[attachment=0]Winter.jpg[/attachment]

where Winter.jpg can be any text.

However, I am getting some PHP Notices. I used regexpal.com to construct this, which works there but uses a Javascript REGEX function:

\[attachment=.*?].*\[/attachment]

When I run this code:

$pm_row['message_text'] = preg_replace('\[attachment=.*?\].*\[/attachment\]', '', $pm_row['message_text']);

PHP complains with a notice:

[phpBB Debug] PHP Notice: in file /mail_digests.php on line 841: preg_replace() [function.preg-replace]: Delimiter must not be alphanumeric or backslash

So on a similar line of code, I delimit the pattern with a "/":

$post_row['post_text'] = preg_replace('/\[attachment=.*?].*\[/attachment]/', '', $post_row['post_text']);

But this generates the following:

[phpBB Debug] PHP Notice: in file /mail_digests.php on line 957: preg_replace() [function.preg-replace]: Unknown modifier 'a'

Any ideas about how to fix this?


You need to escape every occurrence of the delimiter inside the pattern:

If the delimiter needs to be matched inside the pattern it must be escaped using a backslash. If the delimiter appears often inside the pattern, it is a good idea to choose another delimiter in order to increase readability.

So escape it:

'/\[attachment=.*?].*\[\/attachment]/'
                       ^

By the way: Currently the quantifier in .* is greedy, that means it will match as much as possible. You might want to change it to an ungreedy variant using ? like you did before.


You need a delimeter, and you need to escape it if you're actually using it in your expression (i.e.: [/attachment] has a / in it). Escape it or change your delimiter (# for example).


I think I solve this. My test data in the example was bad, so I was trying to match an invalid pattern.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜