将页面标题中的双连字符替换为单连字符


Replace double hyphens in page title with single hyphen

我有这样的页面标题:

$pageTitle = "<title>site - {$cat} - {$q} - {$prod} - {$prodName}</title>";
$pageTitle = str_replace(' - - ', ' - ', $pageTitle);    
echo $pageTitle;

有时这个回声页面的标题是这样的:

<title>site - SportingGoods - Airbed -  - SportingGoods</title>    

当这种情况发生时,其中一个vars为空,我想删除空的带有单个连字符的双连字符。我以为像str_replace这样的东西在这里会起作用,但事实并非如此。

提前谢谢。

当其中一个为空时,连字符之间将有两个空格(而不是一个):

$pageTitle = str_replace(' -  - ', ' - ', $pageTitle);
// Double space! Copy & paste is your friend!
$pageTitle = str_replace(' -  - ', ' - ', $pageTitle);

要解决完整的问题,请使用以下方法:

$titleParts = array($cat, $q, $prod, $prodName);
$titleParts = array_unique($titleParts);
$pageTitle  = implode(' - ', $titleParts);
$pageTitle  = str_replace(' -  - ', ' - ', $pageTitle);