繁体   English   中英

与正则表达式一起使用php preg_replace

[英]using php preg_replace with regex

我创建了一个php正则表达式来查找字符串中的所有注释/ * * /,该字符串在使用此测试工具http://regexpal.com/进行测试时有效

/\*(.*\s){0,}.*\*\/

然后,我用定界符#包围了它,因此它可以与preg_replace一起使用,但是现在不起作用。

#/\*(.*\s){0,}.*\*\/#

$fileContents = preg_replace("#/\*(.*\s){0,}.*\*\/#","Replacement Text",$fileContents);

当我回显$ fileContents时,什么也没打印出来。 我究竟做错了什么?

<?php 
  $fileContents = "Hello /* comment here */ World"; 
  $fileContents = preg_replace('#\/\*.*\*\/#m','',$fileContents); 
  echo $fileContents; // outputs Hello World

  $fileContents = <<<END
Hello
/*
 * Comment spanning several lines..
 *
 */
Earth
END;

  $fileContents = preg_replace('#\/\*.*\*\/#m','',$fileContents); 
  echo $fileContents; // outputs Hello Earth
?> 

正则表达式末尾的m将匹配“多行”,因此当注释跨越多行时,它仍然可以匹配它们。 默认匹配为单行。

请参阅PCRE作为参考: http : //www.php.net/manual/zh/reference.pcre.pattern.modifiers.php

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM