简体   繁体   中英

Search and replace words in a string with regular expression

I have a string like this:

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

I want to replace that words wrapped by @[]

So my result has to be like this:

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

I'm using PHP.

You can make use of regular expressions for the pattern and replace your string using preg_replace .

Something like this,

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

You can also write this in a single line,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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