此正则表达式为真但在本地主机中不起作用

this regex is true but does not work in localhost

我有一个正则表达式,我在 regepr and regex101

中对其进行了测试

但它在本地主机上不起作用!(我的 xampp 版本是 7.0.6) 我的代码是下面的代码

html.html

{block content
ddggggggggggggggg
/endcontent}

file.php

$pt="~\{\s*block\s*-?\s*(\w+)[\s+|\~](.*)\/end}~s";
#Blocks#
preg_match($pt, file_get_contents('html.html'),$match1);
print_r($match1);exit;

我猜问题是 \1 因为下面的代码可以正常工作

$pt="~\{\s*block\s*-?\s*(\w+)[\s+|\~](.*)\/endcontent}~s";
#Blocks#
preg_match($pt, self::$tmp,$match1);
print_r($match1);exit;

为什么第一个代码在我的本地主机上不起作用? 你知道问题出在哪里吗?

html.html 文件不是静态的,可能有所不同我需要一个动态正则表达式,例如第一个正则表达式

您需要使用单引号文字使 </code> 被视为反向引用(否则,您需要对其进行双重转义)。</p> <p>此外,要匹配 1+ 个空格或 <code>~,您需要使用带括号的 grouping,而不是字符 class。请注意 [\s+|\~] 匹配 1 个字符:空格、+|~,我怀疑您是否真的想要这种行为。

使用

$s = "{block content\nddggggggggggggggg\n/endcontent}";
$pt='~\{\s*block\s*-?\s*(\w+)(\s+|\~)(.*)\/end}~s';
preg_match($pt, $s, $match1);
print_r($match1);

IDEONE demo