2017-09-12 16 views
1

に変数から終わるの特定と単語を削除します。現在、私はこのコードを持っているPHP

// main title of product 
$maintitle = 'CHICKENBUFFET HOT WINGS'; 

// take first word from $maintitle and put in new variable 
list($title1) = explode(' ', $maintitle); 

// words that start with CHICKEN are removed and put in new variable 
$title2 = preg_replace('/(CHICKEN)\w+/', '', $maintitle); 

// echo titles 
echo $title1; 
echo $title2; 

これは正常に動作します、しかし、私はビュッフェで終わるCHICKENで始まる単語が、単語を削除する必要はありません。私はそれが私のREGEXとpreg_replace行に何かを持っていると思うが、私は正しい表現を見つけることができない。

ありがとうございます!

+0

それは非常に明確ではありません出力されます

<?php // main title of product $maintitle = 'CHICKENBUFFET HOT WINGS'; // take first word from $maintitle and put in new variable list($title1) = explode(' ', $maintitle); // words that start with CHICKEN are removed and put in new variable $title2 = preg_replace('/\w+BUFFET/', '', $maintitle); // echo titles echo $title1."\n"; echo trim($title2); 

。 ['preg_replace( '/ \ b \ w * BUFFET \ b /'、 '、$ maintitle)'](https://ideone.com/3peOX4)? –

+0

括弧の中に 'CHICKEN'を置く必要はなく、' 'CHICKEN''が'/^ CHICKEN/'である単語にマッチする' regex'があります。 '^'がなければ、文字列の途中で 'CHICKEN'とマッチします。 – axiac

+0

...もしかすると私は誤読したかもしれません。あなたは 'buffet'を保存しますか? – chris85

答えて

2

は、この正規表現を試してみてください:

#\w+BUFFET#

ビュッフェで終わる任意の単語ます一致。

CHICKENBUFFET 
HOT WINGS 

ここでそれを試してみてください:https://3v4l.org/FbMjk

+1

いいえ、それはAnythingEndingInBUFFETと一致します – delboy1978uk

+1

私は文字列に別のBUFFETを追加しました。それが残っています。 https://3v4l.org/CApMM – delboy1978uk

+0

ありがとう!これは私が作ろうとしていたものです。 – SmashingJummy

2

あなたはビュッフェ式の文字列末尾が

$title2 = preg_replace('/\w+(BUFFET)/', '', $maintitle); 

全コード以下のように変更を加える必要があるとして

$maintitle = 'CHICKENBUFFET HOT WINGS'; 

// take first word from $maintitle and put in new variable 
list($title1) = explode(' ', $maintitle); 

// words that start with CHICKEN are removed and put in new variable 
$title2 = preg_replace('/\w+(BUFFET)/', '', $maintitle); // changed this line 

// echo titles 
echo $title1; 
echo "<br/>"; 
echo $title2; 
関連する問題