簡體   English   中英

使用正則表達式搜索並替換字符串中的單詞

[英]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]");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM