preg_match('/.*MyString[ (\/]*([a-z0-9\.\-]*)/i', $contents, $matches);
我需要调试这个。我很清楚它在做什么,但由于我从来都不是正则表达式方面的专家,所以我需要您的帮助。
你能逐 block 告诉我它的作用吗(这样我就可以学习)?
语法是否可以简化(我认为不需要用斜杠转义点)?
最佳答案
正则表达式...
'/.*MyString[ (\/]*([a-z0-9\.\-]*)/i'
.*
匹配任意字符零次或多次
MyString
与该字符串匹配。但是您使用的是不区分大小写的匹配,因此匹配的字符串将拼写为“mystring”,但可以使用任何大小写
编辑:(感谢 Alan Moore)[ (\/]*
。这与任何字符 space
(
或 /
重复零次或多次。正如 Alan 指出的,/
的最终转义是阻止 /
被视为正则表达式分隔符。
编辑: (
不需要转义,.
也不需要转义(感谢 AlexV),因为:
All non-alphanumeric characters other than \, -, ^ (at the start) and the terminating ] are non-special in character classes, but it does no harm if they are escaped. -- http://www.php.net/manual/en/regexp.reference.character-classes.php
连字符,一般需要转义,否则会尝试定义一个范围。例如:
[A-Z] // matches all upper case letters of the aphabet
[A\-Z] // matches 'A', '-', and 'Z'
但是,连字符位于列表末尾的位置,您可以不转义它(但最好始终养成转义它的习惯......我被这个捕获了]。
([a-z0-9\.\-]*)
匹配包含字符 a 到 z 的任何字符串(再次注意,这受到不区分大小写的匹配的影响)、0 到 9、一个点,一个连字符,重复零次或多次。周围的 ()
捕获该字符串。这意味着 $matches[1]
将包含 [a-z0-9\.\-]*
匹配的字符串。括号()
告诉preg_match
“捕获”这个字符串。
例如
<?php
$input = "aslghklfjMyString(james321-james.org)blahblahblah";
preg_match('/.*MyString[ (\/]*([a-z0-9.\-]*)/i', $input, $matches);
print_r($matches);
?>
输出
Array
(
[0] => aslghklfjMyString(james321-james.org
[1] => james321-james.org
)
请注意,因为您使用不区分大小写的匹配...
$input = "aslghklfjmYsTrInG(james321898-james.org)blahblahblah";
也会在 $matches[1]
中匹配并给出相同的答案
希望这有帮助......
关于php - 您能解释/简化 PHP 中的正则表达式 (PCRE) 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16611272/