doucong3048 2016-06-02 16:26
浏览 96
已采纳

PHP str_replace正在替换,但正在清除文本的其余部分

I am using str_replace to replace a substring of a string however, the replacing happens but the rest of the text is disappearing.

Example of $log_text is %%clinicid=1%% clinic we have five rooms.

function strafter($string, $substring) {
  $pos = strpos($string, $substring);
  if ($pos === false)
   return $string;
  else  
   return(substr($string, $pos+strlen($substring)));
}

$log_text = '%%clinicid=1%% clinic has <b>5</b> rooms.';

if (strpos($log_text, '%%clinicid=') !== false) {
    $clinicid = strafter($log_text,'%%clinicid='); 
    $clean_clinicid = str_replace('%%','',$clinicid);
    $clinicname = $db->single("SELECT clinic_name FROM dg_clinics WHERE id = :id", array("id"=>"$clean_clinicid"));

    $clinic_id_string = '%%clinicid='.$clinicid;

    $log_text = str_replace($clinic_id_string,$clinicname,$log_text);

}

The above code gives

Aaa

only not the full text, instead of

Aaa clinic has 5 rooms.

Where am I doing wrong?

PS. if I use %%clinicid=1%% it works perfectly but with a string it doesn't work.

  • 写回答

2条回答 默认 最新

  • doutao6653 2016-06-02 22:01
    关注

    Use preg_match to get clinic id and patern for str_replace

    $log_text = '%%clinicid=1%% clinic has <b>5</b> rooms.';
    
    if (preg_match('/%%clinicid=(\d)%%/', $log_text, $m) !== false) {
       $clean_clinicid = $m[1] ."
    ";
       $clinicname = $db->single("SELECT clinic_name FROM dg_clinics WHERE id = :id", array("id"=>"$clean_clinicid"));
       $log_text = str_replace($m[0],$clinicname,$log_text);
    }
    echo $log_text;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dongqin1167 2016-06-02 19:52
    关注

    You should echo out what you get for your http://php.net/manual/en/function.str-replace.php

    echo "$clinic_id_string<br>";
    echo "$clinicname<br>";
    echo "$log_text<br>";
    

    that should give you a hint of why it doesnt work.

    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 webapi的部署(标签-服务器)
  • ¥20 怎么加快手机软件内部计时的时间(关键词-日期时间)
  • ¥15 C语言除0问题的检测方法
  • ¥15 为什么四分管的内径有的是16mm有的15mm,四分不应该是12.7mm吗
  • ¥15 macos13下 ios交叉编译的问题
  • ¥15 bgz压缩文件怎么打开
  • ¥15 封装dll(引入了pcl的点云设计库)
  • ¥30 关于#开发语言#的问题:我需要在抄板的基础上再抄板抄程序,根据RDA8851CM基础上开发
  • ¥15 oracle 多个括号,怎么删除指定的括号及里面的内容?
  • ¥15 小新14API2019想用bios调风扇