我正在将HTML文件加载到一个变量中,并将其作为匹配的字符串在preg_match中使用。
现在,我需要的是转义所有存在的特殊字符,使其与regex一起工作。
TAB => \t
NEWLINE => \n
CARRIEG RETURN => \r
CARRIEG RETURN+NEWLINE => \n
VERTICAL TAB => \cK
and other special characters...例如,这个HTML文件
text \text text <tag attr="val"> text </tag>
text text $ ^ text
{} text text text
text | text将转换为
text \\text text \<tag attr\=\"val\"\> text \<\/tag\> \ntext text \$ \^ text\n\{\} text text text \ntext \| text有一些内置的功能可以让我的生活更轻松?
更新:
我使用这个函数使regex函数可以访问字符串,这些函数看起来工作正常:
private function real_regular_expression_string($text) {
// Escape backslashes
$text = preg_replace('/[\\\\]/', '\\\\', $text);
// Escape regular expression special character
$text = preg_quote($text, '/');
// Search and Replace variable for another special characters
$search = [
"\n", // 2 - New line character
"\r", // 3 - Carriage-Return character
"\t", // 4 - Horizontal tab character
"\v", // 5 - Vertical tab character
"\e", // 6 - Escape character
"\f", // 7 - Form-feed character
];
$replace = [
'\n', // 2
'\r', // 3
'\t', // 4
'\cK', // 5
'\a', // 6
'\f', // 7
];
$text = str_replace($search, $replace, $text);
// A littel fix
$text = str_replace('\r\n', '\n', $text);
return $text;
}知道怎么做才能更好吗?
但是,现在preg_match不能正常工作:\
我从上面的函数中得到了这个正则字符串:
/(?:(?:.*)(?:\r\n|\r|\n))*(?<offset>.*)(?:\$\{ALMdOG \= \n\t\$\{ALMdOG\} \n\})/HTML文件是:
text text text text
numerofcharacters ${ALMdOG =
${ALMdOG}
}
text text text text
text text text text
text text text text 哪个应该起作用并且停止我的痛苦,有什么想法吗?
发布于 2019-09-02 17:53:44
https://stackoverflow.com/questions/57761005
复制相似问题