我不太擅长正则表达式。
我有很多文件里面有一个重复的字符串:
$find = "><script contentType="application/x-javascript"n>nnif(event.target.hostContainer)";
但是有时候你在上面的字符串中看到的不是2 n
,而是3或1。当然,这是一个必须克服的愚蠢问题,但不幸的是,该文件是pdf…所以我不能控制它的输出。
我该如何搜索上面的字符串而忽略n
。
我的问题的上下文是:
$file = file_get_contents('pdfs/another1.pdf');
$find = "><script contentType="application/x-javascript"n>nnif(event.target.hostContainer)";
$replace = "whatever bla bla";
$output_str = str_replace($find, $replace, $file);
一方面,str_replace
不使用正则表达式作为搜索字符串。正确的函数是preg_replace
下面是一个在这种情况下工作的正则表达式:
$find = '#><script contentType="application/x-javascript"s*>s*if(event.target.hostContainer)#U';
$output_str = preg_replace($find, $replace, $file);
regex有很多""(转义)字符,因为"。"、"("one_answers")"在regex中有特殊的含义。正则表达式用"#"分隔符括起来。正则表达式末尾的'U'修饰符是一种预防措施,因此,如果字符串有多个匹配表达式,每个匹配将被替换为替换。
PHP regex的完整解释在这里:http://us1.php.net/manual/en/reference.pcre.pattern.syntax.php