PHP str_replace替换&字符' - '

时间:2014-07-04 00:40:32

标签: php regex

这是我的代码

$Meeting="4181211";
$EventID="Wanganui";
$Description="G Bristol & Sons (Bm75)";
$entities = array(' ', '%28', '%29');
$replacements = array('-',"(", ")");
echo str_replace($entities,$replacements, strtolower("https://www.ladbrokes.com.au/racing/greyhounds/".$Meeting."/".$EventID."-".$Description."/"));

输出就像

https://www.ladbrokes.com.au/racing/greyhounds/4181211/wanganui-g-bristol-&-sons-(bm75)/ 

这很好,但在我的其他情况下

$Meeting="4222658";
$EventID="Yonkers";
$Description="Yonkers Raceway F&M Clm Pce Ms";
$entities = array(' ', '%28', '%29');
$replacements = array('-',"(", ")");
echo str_replace($entities,$replacements, strtolower("https://www.ladbrokes.com.au/racing/greyhounds/".$Meeting."/".$EventID."-".$Description."/"));

输出类似于https://www.ladbrokes.com.au/racing/greyhounds/4222658/yonkers-yonkers-raceway-f&m-clm-pce-ms/

但这是一个问题,我希望我的输出像https://www.ladbrokes.com.au/racing/greyhounds/4222658/yonkers-yonkers-raceway-f-m-clm-pce-ms/

我只想查看描述是否没有空格(之前/之后)'&'然后它应该被替换为' - '。例如,在f& m的情况下,我想要像f&m;'布里斯托尔& Sons就像Bristol-& -Sons一样很好,而且()在输出中没有被%28和%29取代任何建议吗?

1 个答案:

答案 0 :(得分:1)

如果你想要做的只是在原始描述中用&替换-;只需在构建完整URL之前执行此操作:

$Description=preg_replace("/(\w)&(\w)/",'$1-$2',"Yonkers Raceway F&M Clm Pce Ms");
// => //www.ladbrokes.com.au/racing/greyhounds/4222658/yonkers-yonkers-raceway-f-m-clm-pce-ms/

和另一个案例,你得到:

$Description=preg_replace("/(\w)&(\w)/", "$1-$2", "G Bristol & Sons (Bm75)");
// => https://www.ladbrokes.com.au/racing/greyhounds/4222658/yonkers-g-bristol-&-sons-(bm75)/
相关问题