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条)

报告相同问题?