Reputation: 99
i have a regex and I test it in regepr and regex101
but it is not work in localhost!(my xampp version in 7.0.6) my code is the following code
html.html
{block content
ddggggggggggggggg
/endcontent}
file.php
$pt="~\{\s*block\s*-?\s*(\w+)[\s+|\~](.*)\/end\1}~s";
#Blocks#
preg_match($pt, file_get_contents('html.html'),$match1);
print_r($match1);exit;
I am guessing the problem is \1 because the following code is work correctly
$pt="~\{\s*block\s*-?\s*(\w+)[\s+|\~](.*)\/endcontent}~s";
#Blocks#
preg_match($pt, self::$tmp,$match1);
print_r($match1);exit;
why first code is does not work in my localhost? do you know what is the problem?
html.html file is not static and maybe diffrent I need a dynamic regex such as first regex
Upvotes: 2
Views: 161
Reputation: 627100
You need to use a single quoted literal to make \1
be treated as a backreference (otherwise, you need to double escape it).
Also, to match either 1+ whitespaces or a ~
you need to use grouping with parentheses, not a character class. Note that [\s+|\~]
matches 1 character: a whitespace, a +
, |
or a ~
, and I doubt you actually want that behavior.
Use
$s = "{block content\nddggggggggggggggg\n/endcontent}";
$pt='~\{\s*block\s*-?\s*(\w+)(\s+|\~)(.*)\/end\1}~s';
preg_match($pt, $s, $match1);
print_r($match1);
See the IDEONE demo
Upvotes: 2