PHP 正则表达式抓取 {tag}something{/tag}
我正在尝试使用正则表达式字符串来与 PHP preg 函数(preg_match 等)一起使用,并且对此感到困惑:
如何匹配此字符串?:
{area-1}some text and maybe a <a href="http://google.com">link</a>.{/area-1}
我想使用 preg_replace 将其替换为不同的字符串。
到目前为止,我已经能够使用 preg_match 识别第一个标签,如下所示:
preg_match("/\{(area-[0-9]*)\}/", $mystring);
如果您能提供帮助,谢谢!
I'm trying to come=up with a regex string to use with the PHP preg functions (preg_match, etc.) and am stumped on this:
How do you match this string?:
{area-1}some text and maybe a <a href="http://google.com">link</a>.{/area-1}
I want to replace it with a different string using preg_replace.
So far I've been able to identify the first tag with preg_match like this:
preg_match("/\{(area-[0-9]*)\}/", $mystring);
Thanks if you can help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您没有嵌套标签,那么这样简单的事情应该可以工作:
您的结果可以在
$matches[1]
中找到。If you don't have nested tags, something this simple should work:
Your results can be then found in
$matches[1]
.我建议
如果其他标签嵌套在您正在查看的
area
标签内,这甚至可以工作。如果您有多个相互嵌套的
area
标记,它仍然可以工作,但您需要多次应用正则表达式(每个嵌套级别一次)。当然,匹配的内容将在
$matches[2]
中,而不是 Tatu 的答案中的$matches[1]
中。I would suggest
This will even work if other tags are nested inside the
area
tag you're looking at.If you have several
area
tags nested within each other, it will still work, but you'll need to apply the regex several times (once for each level of nesting).And of course, the contents of the matches will be in
$matches[2]
, not$matches[1]
as in Tatu's answer.