Ali
Ali

Reputation: 3

using php preg_replace with regex

I created a php regex to find all comments /* */ in a string which works as I tested it using this test tool http://regexpal.com/

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

I then surrounded it with delimiters # so it works with preg_replace however now it doesn't work.

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

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

When I echo out $fileContents nothing is printed out. What am I doing wrong?

Upvotes: 0

Views: 487

Answers (1)

Dexter Huinda
Dexter Huinda

Reputation: 1222

<?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
?> 

The m at the end of the regex will match "multi-line", so that when comment spans on several lines, it can still match them. Default match is single line.

See PCRE for your reference: http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php

Upvotes: 0

Related Questions