php:将特定单词与字符串中的相同单词匹配并删除它

时间:2015-04-02 07:02:03

标签: php

字符串示例。

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

我正在尝试从字符串

中删除\ tmp

结果:Olyus Stylus VG-165.

它从字符串末尾和奥林匹克中删除'mp'。

我怎样才能从末尾删除mp,但也不从奥林巴斯删除

欲望输出:Olympus Stylus VG-165.

2 个答案:

答案 0 :(得分:1)

使用这个简单的单行

echo substr("Olympus Stylus VG-165 mp",0,22);

答案 1 :(得分:1)

$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