PHP Regex函数用于查找和替换字符串中的单词

时间:2011-03-26 01:35:10

标签: php regex

嗨我有电影片头,我希望在“DVD”或Bluray开头之前的“空白空间”之后删除所有内容。 例如,我有以下字符串

Avatar DVD 2009
War of the Roses DVD 1989 Region 1 US import
Wanted Bluray 2008 US Import

输出

=====
Avatar
War of the Roses

=======

5 个答案:

答案 0 :(得分:2)

$result = preg_replace('/ (DVD|BLURAY).*/i', '', $input);

答案 1 :(得分:1)

这是命令:

preg_replace('( (DVD|Bluray).*$)', '', 'Wanted Bluray 2008 US Import')

基本上,我们选择一个空格,单词“DVD”或单词“Bluray”然后任何东西,直到字符串的结尾,并用任何东西替换它(从而删除它们)。简单地把它放在循环中应该适合你。

希望这有帮助。

答案 2 :(得分:1)

从Jason的回答中更新了电影标题列表

试试这个(假设标题列表是一个字符串):

$titles = "Avatar DVD 2009
War of the Roses DVD 1989 Region 1 US import
Wanted Bluray 2008 US Import
This Bluray is Wanted DVD 2008 US Import
This DVD is Wanted Bluray 2008 US Import";

$filteredTitles = array_map(function($title) { 
    return preg_replace('/^(.+) ((?:DVD|Bluray) .+)$/', '$1', $source)
}, explode(PHP_EOL, $titles));

echo $filteredTitles; 

/*
Avatar
War of the Roses
Wanted Bluray 2008 US Import
This Bluray is Wanted
This DVD is Wanted
*/

答案 3 :(得分:0)

如果您不想要正则表达式(包括跟随xzyfer评论的strripos()):

<?php 

function stripTypeTitle($title) {
    $dvdpos = strripos($title, 'dvd');
    $bluraypos = strripos($title, 'bluray');
    if ($dvdpos !== false && $dvdpos > $bluraypos) {
        $title = substr($title, 0, $dvdpos);
    }
    if ($bluraypos !== false && $bluraypos > $dvdpos) {
        $title = substr($title, 0, $bluraypos);
    }
    return $title;
}

$title = "Avatar DVD 2009";
echo stripTypeTitle($title)."<br/>";
$title = "War of the Roses DVD 1989 Region 1 US import";
echo stripTypeTitle($title)."<br/>";
$title = "Wanted Bluray 2008 US Import";
echo stripTypeTitle($title)."<br/>";
$title = "This Bluray is Wanted DVD 2008 US Import";
echo stripTypeTitle($title)."<br/>";
$title = "This DVD is Wanted Bluray 2008 US Import";
echo stripTypeTitle($title)."<br/>";

?>

打印:

Avatar
War of the Roses
Wanted
This Bluray is Wanted
This DVD is Wanted 

答案 4 :(得分:-1)

$title = preg_replace('/ (DVD|Bluray) /',' ' ,$title);