php新手问题:正则表达式
抱歉,我已经提出了这个要求,但尚未找到解决方案:( 这是我的字符串:(如您所见,它有换行符)
Webname: [webname]
Username: [username]
IP: [IP]
我需要读出方括号内的值。 这是我的代码:
$pattern = '/\[(.|\n)+?\]/'; // i've used the same syntax for my asp projects, always worked
preg_match($pattern, $txt, $matches, PREG_OFFSET_CAPTURE);
echo "matches:".count($matches)."\n\n";
foreach ($matches as $match)
{
echo $match[0]."\n";
}
我只得到 2 个匹配项:[webname]
和 e
(???) 我已经摆弄这个好几个小时了,无法找出问题所在..
有什么想法吗? 谢谢
i'm sorry i've already asked for this but couldn't find a solution yet :(
here's my string: (as you can see it has linebreaks)
Webname: [webname]
Username: [username]
IP: [IP]
i need to read out the values inside the square brackets.
here's my code:
$pattern = '/\[(.|\n)+?\]/'; // i've used the same syntax for my asp projects, always worked
preg_match($pattern, $txt, $matches, PREG_OFFSET_CAPTURE);
echo "matches:".count($matches)."\n\n";
foreach ($matches as $match)
{
echo $match[0]."\n";
}
i'm getting only 2 matches: [webname]
and e
(???)
i'm fiddling with this for hours now and can't find out what's wrong ..
any ideas?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看起来比实际情况更复杂。换行符在这里不起作用。
给出
所以值将在
$matches[1]
中。如果您想要包含括号的值 ($matches[0]
),您也可以在模式中省略括号。Looks more complicated than it has to be. Line breaks don't play any role here.
gives
So the values would be in
$matches[1]
. If you want the values including the brackets ($matches[0]
), you can also omit the parenthesis in the pattern.第一个捕获组(在您的情况下只有一个)位于
$matches[1]
中The first capture group, in your case there is only one, is in
$matches[1]
尝试类似的方法
并使用 preg_match_all() 来获取所有匹配项。
Try something like
and use preg_match_all() to get all matches.
试试这个
Try this