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

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.

图片转代码服务由CSDN问答提供 功能建议

我使用str_replace替换字符串的子字符串但是,替换发生但文本的其余部分正在消失 。

$ log_text的示例是 %% clinicid = 1 %%诊所我们有五个房间。

  function strafter($ string,$ substring){
 $ pos = strpos($ string,$ substring); 
 if($ pos === false)
 return $ string; 
 else 
 return(substr  ($ string,$ pos + strlen($ substring))); 
} 
 
 $ log_text ='%% clinicid = 1 %%诊所已经&lt; b&gt; 5&lt; / b&gt; 房间。'; 
 
if(strpos($ log_text,'%% clinicid =')!== false){
 $ clinicid = strafter($ log_text,'%% clinicid =');  
 $ clean_clinicid = str_replace('%%','',$ clinid); 
 $ clinicname = $ db-&gt; single(“SELECT clinic_name FROM dg_clinics WHERE id =:id”,array(“id”=&gt;  ;“$ clean_clinicid”)); 
 
 $ clinic_id_string ='%% clinicid ='。$ clinid; 
 
 $ log_text = str_replace($ clinic_id_string,$ clinicname,$ log_text); 
 
} \  n   
 
 

上面的代码给出了

Aaa n

不是全文,而不是

Aaa诊所有 5 个房间。

我在哪里做错了?

PS。 如果我使用 %% clinicid = 1 %% 它可以很好地工作但是使用字符串它不起作用。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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.

    点赞 评论

相关推荐 更多相似问题