使用正则表达式搜索和替换字符串中的单词

Search and replace words in a string with regular expression

我有这样一个字符串:

"This is a random string with @[certain] words with this format @[something]"

我想替换 @[]

包裹的那些词

所以我的结果必须是这样的:

"This is a random string with words with the format"

我正在使用 PHP。

您可以对模式使用正则表达式并使用 preg_replace 替换您的字符串。

像这样,

$str = "This is a random string with @[certain] words with this format @[something]";
$newStr = preg_replace('/\ @\[(\w+)\]/','',$str);

你也可以写成一行,

echo preg_replace('/\ @\[(\w+)\]/','',"This is a random string with @[certain] words with this format @[something]");