从 PHP 中的变量中删除具有特定结尾的单词
Remove words with specific ending from variable in 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 开头的单词,而是删除以 BUFFET 结尾的单词。我认为它与我在 preg_replace 行中的正则表达式有关,但我似乎找不到正确的表达式。
提前致谢!
由于您需要以 BUFFET 结尾的字符串,请进行如下更改
$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;
试试这个正则表达式:
#\w+BUFFET#
任何以 BUFFET 结尾的单词都会匹配。
<?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);
这将输出:
CHICKENBUFFET
HOT WINGS
在这里试试:https://3v4l.org/FbMjk
目前我有这个代码:
// 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 开头的单词,而是删除以 BUFFET 结尾的单词。我认为它与我在 preg_replace 行中的正则表达式有关,但我似乎找不到正确的表达式。
提前致谢!
由于您需要以 BUFFET 结尾的字符串,请进行如下更改
$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;
试试这个正则表达式:
#\w+BUFFET#
任何以 BUFFET 结尾的单词都会匹配。
<?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);
这将输出:
CHICKENBUFFET
HOT WINGS
在这里试试:https://3v4l.org/FbMjk