dpkt31779 2014-07-04 00:40
浏览 22
已采纳

PHP str_replace用' - '替换&字符

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-f-m-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 'f-m' while Bristol & Sons is coming like Bristol-&-Sons which is fine and ( ) are not replaced with %28 and %29 in the output any suggestions?

  • 写回答

1条回答 默认 最新

  • dqp21271 2014-07-04 00:47
    关注

    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)/
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog