2016-04-02 23 views
2

私はトークンの内容を持ち、のテストで始まらないすべてのトークンを削除したいと思います。PHP preg_replace - 正規表現(トークンを削除する)

$content = 'Hello [test:username]. What are you [token:name]'; 
$string = preg_replace('/\[test(.*)\]/', '', $content); 

この作品が、空の文字列でテストで始まるすべてのトークンを置き換えます。たとえば、私は、コンテンツを持っています。私は反対にしたいのテストで始まりません。正規表現をどのように変更すればよいですか?私はにpreg_replace後、この結果を取得したい:

$content = 'Hello [test:username]. What are you'; 
+0

見る正規表現の文書で、特にあなたのパターンの始めに '^'を使ってください... – Stuart

答えて

1

あなたは、次の正規表現

(?:\[test:[^]]+\])(*SKIP)(*F)|(?:\[\w[^]]+\]) 

を使用することができますので、あなたのコードが

preg_replace('/(?:\[test:[^]]+\])(*SKIP)(*F)|(?:\[\w[^]]+\])/', '', $content); 

として説明のようになります。

(?:\[test:[^]]+\]) // Will capture a group of tokens that have same 
         pattern like as [test:...] 

(*SKIP)(*F)  // This is supported by PCRE to skip the above captured group 

|(?:\[\w[^]]+\]) // This'll capture rest of the group that doesn't 
        contains pattern like as [test:...] 
+1

あなたはようこそです。あなたを助けてくれてうれしいです。 @ user3421014また、将来のユーザーにも説明を追加しました –