PHP正则表达式失败
我目前的正则表达式应该是正确的,但我不期望如此,它不能正常工作。它不会返回“拿到赛” 我currrent代码如下:PHP正则表达式失败
$id = "http://steamcommunity.com/id/TestID";
if (preg_match("^http://steamcommunity\.com/id/.*?\n$", $id)) {
print "Got match!\n";
}
你需要一个分隔符,就像这样:
if (preg_match("#^http://steamcommunity\.com/id/.*?$#", $id)) {
^ ^
并在年底换行符有什么?当然你不需要那个。
您忘记了在url内部转义'/'如果使用'/'作为分隔符,则这是必需的。 –
我编辑帖子十秒前使用不同的分隔符 –
您需要添加的模式定界符:
$id = "http://steamcommunity.com/id/TestID";
if (preg_match("#^http://steamcommunity\.com/id/.*?(\n|$)#", $id)) {
print "Got match!\n";
}
你错过了你的正则表达式的分隔符:
if (preg_match("#^http://steamcommunity\.com/id/.*?\n$#", $id)) {
^--here ^--here
请注意,我用#
作为分隔符这里,因为可以节省如果您使用传统的/
作为分隔符,您必须逃离所有内部的/
charrs。
您需要在模式中使用起始和结束分隔符,如/pattern/
或#pattern#
或括号(pattern)
。这是为什么?有结束符像#pattern#i
后,一些模式修饰符(忽略大小写)
preg_match('(^http://steamcommunity\.com/id/.*?\n$)', $id)
<?php
# URL that generated this code:
# http://txt2re.com/index-php.php3?s=http://steamcommunity.com/id&-1
$txt='http://steamcommunity.com/id';
$re1='(http:\\/\\/steamcommunity\\.com\\/id)'; # HTTP URL 1
if ($c=preg_match_all ("/".$re1."/is", $txt, $matches))
{
$httpurl1=$matches[1][0];
print "($httpurl1) \n";
}
#-----
# Paste the code into a new php file. Then in Unix:
# $ php x.php
#-----
?>
Resorces: http://txt2re.com/index.php3?s=http://steamcommunity.com/id&-1
为什么有一个PHP的问题perl的答案? – NullUserException
我的坏就是一味的抄袭和粘贴哈哈!固定为PHP –
有一对夫妇的事情是错的。首先,你需要用一个字符来分隔你的正则表达式的开始和结束。我用#
。你也可以在你的正则表达式的末尾匹配一个新行,这是你没有的,也可能不会在你的字符串中存在。
<?php
$id = "http://steamcommunity.com/id/TestID";
if (preg_match("#^http://steamcommunity\.com/id/.*?$#", $id)) {
print "Got match!\n";
}
?>
所有的
首先,你的正则表达式甚至不应该编译,因为它缺少分隔符。
if (preg_match("~^http://steamcommunity\.com/id/.*?\n$~", $id)) {
^---- these guys here -----^
所有的二,为什么你有\n
如果字符串不包含一个新行?
最后,为什么你使用正则表达式呢?实际上,你只是想匹配一个常量字符串。这应该相当于你想要匹配的东西:
if (strpos($id, 'http://steamcommunity.com/id/') === 0) {
好一点,虽然我想通逻辑下一步是从该字符串与子模式捕获的ID代码。 – Wiseguy
你可以使用'substr()'来捕获id码 – NullUserException
正如说你的彭定康是开始和结束错误。 (分隔符)
但是,这将是64位Steam ID的更好匹配。(最小17首最大25个数字)
if(preg_match("#^http://steamcommunity\.com/id/([0-9]{17,25})#i", $id, $matches))
{
echo "Got match! - ".$matches;
}
我认为,没有必要为你需要的字符串必须以换行符结束。
说明。
http://steamcommunity\.com/id/([0-9]{17,25})
^--- string ---^^-- Regexp --^
[0-9] - 匹配0之间的一个数到9
{17,25} - 使17至25的匹配
() - 返回匹配
或者使用图案作为那些(这是相同的):
/^http:\/\/steamcommunity\.com\/id\/([0-9]{17,25})/i
(^http://steamcommunity\.com/id/([0-9]{17,25}))i
Regular Expressions PHP Tutorial
Online regular expression testing < - 不使用分隔符。
[将ereg表达式转换为preg]可能的副本(http://*.com/questions/6270004/converting-ereg-expressions-to-preg) – mario