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

时间:2015-11-19 03:08:11

标签: php regex string preg-replace str-replace

我有一个这样的字符串:

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

我想替换@[]

包裹的单词

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

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

我正在使用PHP。

1 个答案:

答案 0 :(得分:1)

您可以使用模式的正则表达式,并使用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]");