使用正则表达式从字符串中提取某些文本
我尝试从字符串中提取编码字符串,例如,
$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]+)(?: |\s)*\](.*?)\[(?: |\s)*([\/date]+)(?: |\s)*\]/is', '$3',$string);
echo $date;
结果:
Louise Bourgeois and Tracey Emin: Do Not Abandon Me /date
预期结果:
Until 31 August 2011
我得到了 $description
正确,但无法得到 [date]
正确。有什么想法吗?
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]+)(?: |\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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为一个更简单的形式就可以了:
例如?
I think a rather simpler form would do:
for instance?
这将查找包含
d
、a
、t
和/或e< 的一个或多个字母序列/代码>。
[]
是字符类的正则表达式元字符,不会被视为用于匹配目的的文字字符。您可能想要:正确匹配那些开始/结束“标签”。
This is going to look for one-or-more sequences of letters containing
d
,a
,t
, and/ore
.[]
are regex metacharacters for character classes and will not treated as literal characters for matching purposes. You'd probably want:to properly match those opening/closing "tags".