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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿
  • ¥15 Matlab在app上输入带有矩阵形式的初始条件发生错误
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址