我目前的正則表達式應該是正確的,但我不期望如此,它不能正常工作。它不會返回「拿到賽」 我currrent代碼如下:PHP正則表達式失敗
$id = "http://steamcommunity.com/id/TestID";
if (preg_match("^http://steamcommunity\.com/id/.*?\n$", $id)) {
print "Got match!\n";
}
我目前的正則表達式應該是正確的,但我不期望如此,它不能正常工作。它不會返回「拿到賽」 我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://stackoverflow.com/questions/6270004/converting-ereg-expressions-to-preg) – mario