从PHP

时间:2017-09-12 08:31:54

标签: php regex preg-replace

目前我有这段代码:

// 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行中与我的REGEX有关,但我似乎无法找到正确的表达式。

谢谢你!

2 个答案:

答案 0 :(得分:2)

因为您需要使用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;

答案 1 :(得分:2)

试试这个正则表达式:

#\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