PHP Regex function to find and replace words from string
Hi I have movie titles and I want to remove everything after the "emp开发者_开发知识库ty space" before the word "DVD" or Bluray begins. So for example I have the following strings
Avatar DVD 2009
War of the Roses DVD 1989 Region 1 US import
Wanted Bluray 2008 US Import
Output
=====
Avatar
War of the Roses
=======
$result = preg_replace('/ (DVD|BLURAY).*/i', '', $input);
Here is the command:
preg_replace('( (DVD|Bluray).*$)', '', 'Wanted Bluray 2008 US Import')
Basically, we select a space, the word "DVD" or the word "Bluray" then anything until then end of the string and replace it with nothing (thus remove them). Simply put this in the loop should work for you.
Hope this helps.
Updated movie title list from Jason's answer
Try this (assuming the list of title is one string):
$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
*/
In case you don't want a regex (including the strripos()
following xzyfer comment):
<?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/>";
?>
Prints:
Avatar
War of the Roses
Wanted
This Bluray is Wanted
This DVD is Wanted
$title = preg_replace('/ (DVD|Bluray) /',' ' ,$title);
精彩评论