简体   繁体   中英

PHP str_replace to replace & character with '-'

This is my code

$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."/"));

The output is coming like

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

which is fine but in my other case

$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."/"));

Output is like https://www.ladbrokes.com.au/racing/greyhounds/4222658/yonkers-yonkers-raceway-f&m-clm-pce-ms/

But here is a problem i want my output like this https://www.ladbrokes.com.au/racing/greyhounds/4222658/yonkers-yonkers-raceway-fm-clm-pce-ms/

I just want to check in the description if there is no spaces (after/before) '&' character then it should be replaced with '-'. For example in f&m case i want like 'fm' while Bristol & Sons is coming like Bristol-&-Sons which is fine and ( ) are not replaced with %28 and %29 in the output any suggestions?

If all you want to do is replace & with - in the original description; just do that before you build the full url by doing:

$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/

and with the other case, you get:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM