1
votes

I am trying to remove everything between two characters, including the two characters, from a string using regex in php. I tried using the answer on this page so now I have a line in my php file which looks like this :

$message = preg_replace('\[[^\]]*]', '', $message);

The problem is I get this error:

Warning: preg_replace() [function.preg-replace]: Delimiter must not be alphanumeric or backslash

How can I fix this?

2
Read the error message, your regular expression pattern is missing a delimiter (in your case, the message means that what PCRE things delimiters are do not match). See php.net/manual/en/regexp.reference.delimiters.php - On the linked page the delimiters have been left out because that is a regular expression in cold fusion, this might differ substantially from PCRE which is used by preg_* functions in PHP. - hakre

2 Answers

4
votes

Regular expressions in PHP need to be delimited:

$message = preg_replace('/\[[^\]]*]/', '', $message);

Check out this documentation.

Also as a side note, you don't need to escape the closing ] if it is the first character in a character class:

$message = preg_replace('/\[[^]]*]/', '', $message);

(Whether that is more readable in this case is debatable. But it's good to know.)

0
votes

This is my solution: let both left and right markers be the quote char. This reg expr splits the query string into three atoms which will be re-arranged as desired into the input string. Hope it helps.

var _str = "replace 'something' between two markers" ;
document.write( "INPUT : " + _str + "<br>" );
_str = _str.replace( /(\')(.*?)(\')/gi, "($1)*some string*($3)" );
document.write( "OUTPUT : " + _str + "<br>" );