PHP str_replace替换&字符'-'


PHP str_replace to replace & character with '-'

这是我的代码

$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',而Bristol &Sons就像Bristol-&-Sons,这很好,()在输出中没有被%28和%29取代,有什么建议吗?

如果您想做的只是将原描述中的&替换为-;在构建完整的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)/