开发者

Extract certain text from a string with regex

I tried to extract a coded string from a string, for instance,

$string = 'Louise Bourgeois and Tracey Emin: Do Not Abandon Me [date]Until 31 August 2011[ /date ]';

$description = preg_replace('/\[(?: |\s)*([date]+)(?: |\s)*\](.*?)\[(?: |\s)*([\/date]+)(?: |\s)*\]/is', '',$string);

$date = preg_replace('/\[(?: |\s)*([date]+)(?:&开发者_运维问答;nbsp;|\s)*\](.*?)\[(?: |\s)*([\/date]+)(?: |\s)*\]/is', '$3',$string);

echo $date;

result:

Louise Bourgeois and Tracey Emin: Do Not Abandon Me /date

intended result:

Until 31 August 2011

I got the $description right but I can't get the [date] right. Any ideas?


I think a rather simpler form would do:

#.*?\[\s*?date\s*?\](.*)\[\s*?/date\s*?\].*#

for instance?


([date]+)

This is going to look for one-or-more sequences of letters containing d, a, t, and/or e. [] are regex metacharacters for character classes and will not treated as literal characters for matching purposes. You'd probably want:

(\[date\])   and    (\[\/date\])

to properly match those opening/closing "tags".

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜