[英]Regular expression that ignores line breaks
我不太擅长正则表达式。
我有各种文件,其中包含重复的字符串:
$find = "><script contentType=\"application/x-javascript\"\n>\n\nif(event.target.hostContainer)";
但是有时在上面的字符串中看到的不是2 \\n
,有时是3或1。当然,必须克服一个愚蠢的问题,但不幸的是该文件是pdf ...所以我没有控制权超过其输出。
我如何在忽略\\n
搜索上述字符串。
我的问题是:
$file = file_get_contents('pdfs/another1.pdf');
$find = "><script contentType=\"application/x-javascript\"\n>\n\nif(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);
正则表达式有很多“ \\”(转义)字符,因为“。”,“(”和“)”在正则表达式中具有特殊含义。 正则表达式包含在“#”定界符中。 正则表达式末尾的'U'修饰符是一种预防措施,因此,如果字符串具有多个匹配表达式,则每次匹配都将替换为替换。
有关PHP正则表达式的完整说明,请参见: http : //us1.php.net/manual/en/reference.pcre.pattern.syntax.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.