Whats wrong in preg_match("/<script>


Whats wrong in preg_match("/<script>

我想找到

"<script> ytplayer" and "ytplayer.config.loaded" .

我的代码如下所示:

preg_match("/'<script'>var's+ytplayer.+?ytplayer'.config'.loaded/", 
$file_contents, $videosource);

创建一个捕获组:

preg_match("/'<script'>var's+ytplayer(.+?)ytplayer'.config'.loaded/", $file_contents, $videosource);
//           note the parens      ___^ __^

捕获将在$videosource[1]

应该是…

preg_match("/''<script''> ytplayer(.+)ytplayer''.config''.loaded/", $file_contents, $videosource);

注意双转义。你必须使用两个反斜杠,因为"'<"<的意思一样,而"''<"'<的意思一样。正如M42所指出的,你应该在中间的东西周围分组。这使得中间部分在$videosource[1]中可用。

如果希望匹配不区分大小写,可以使用

preg_match("/''<script''> ytplayer(.+)ytplayer''.config''.loaded/i", $file_contents, $videosource);

regex结尾的i使其不区分大小写。

RegEx是文字,除非您使用通配符。只使用必要的部分可能更容易。为此,您可以使用带有原子分组的遍历。

$pattern = "!(?<=(ytplayer)).*(?=(ytplayer))!";
preg_match($pattern,$file_contents,$matches);
$videosource = $matches[0];