php:将特定单词和字符串中的相同单词进行匹配并将其删除


php: match specific word with same word from string and remove it

字符串示例。

$val = "Olympus Stylus VG-165 mp";

我正试图从字符串中删除mp

结果:Olyus Stylus VG-165.

它删除了字符串末尾的"mp",也删除了奥林巴斯。

我怎么能从末端移除mp,但也不能从奥林巴斯移除

所需输出:Olympus Stylus VG-165.

使用这个简单的单行

echo substr("Olympus Stylus VG-165 mp",0,22);
$var = preg_replace('# mp$#',' ',$var) ; // Remove if there is " mp" at the end
$var = preg_replace('#^mp #',' ',$var) ; // Remove if "mp " on start
$var = preg_replace('# mp #',' ',$var) ; // Remove if " mp " everywhere
$var = trim($var) ; // Remove the extras space on start and end of the string

另一种方法:

function testMp($v) { return $v != 'mp' ; } // Function called by array_filter
$words = explode(' ',$var) ; // Explode the words of the string in an array
$words = array_filter($words,'testMp') ; // Test each word on the array and remove if "mp" found (via testMp)
$var = implode(' ',$words) ; // Restore the words array into a simple string