简体   繁体   English

使用php中的regex替换两个字符之间的所有内容

[英]Replace everything between and including two characters using regex in php

I am trying to remove everything between two characters, including the two characters, from a string using regex in php. 我试图从使用PHP中的正则表达式的字符串中删除两个字符之间的所有内容,包括两个字符。 I tried using the answer on this page so now I have a line in my php file which looks like this : 我尝试使用此页面上的答案,所以现在我的php文件中有一行,如下所示:

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

The problem is I get this error: 问题是我收到此错误:

Warning: preg_replace() [function.preg-replace]: Delimiter must not be alphanumeric or backslash 警告:preg_replace()[function.preg-replace]:分隔符不能是字母数字或反斜杠

How can I fix this? 我怎样才能解决这个问题?

Regular expressions in PHP need to be delimited: PHP中的正则表达式需要分隔:

$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.) (在这种情况下,这是否更具可读性是值得商榷的。但要知道这一点很好。)

This is my solution: let both left and right markers be the quote char. 这是我的解决方案:让左右标记都是引号char。 This reg expr splits the query string into three atoms which will be re-arranged as desired into the input string. 此reg expr将查询字符串拆分为三个原子,这些原子将根据需要重新排列到输入字符串中。 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>" );

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

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