PHP str_replace 正在替换但清除其余文本
PHP str_replace is replacing but clearing the rest of the text
我正在使用 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%% 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);
}
以上代码给出
Aaa
只不是全文,而不是
Aaa clinic has 5 rooms.
我哪里做错了?
PS。如果我使用 %%clinicid=1%%
它可以完美地工作但是使用字符串它不起作用。
你应该回显你的 http://php.net/manual/en/function.str-replace.php
echo "$clinic_id_string<br>";
echo "$clinicname<br>";
echo "$log_text<br>";
这应该会提示您为什么它不起作用。
使用 preg_match 获取 str_replace
的诊所 ID 和模式
$log_text = '%%clinicid=1%% clinic has <b>5</b> rooms.';
if (preg_match('/%%clinicid=(\d)%%/', $log_text, $m) !== false) {
$clean_clinicid = $m[1] ."\n";
$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;
我正在使用 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%% 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);
}
以上代码给出
Aaa
只不是全文,而不是
Aaa clinic has 5 rooms.
我哪里做错了?
PS。如果我使用 %%clinicid=1%%
它可以完美地工作但是使用字符串它不起作用。
你应该回显你的 http://php.net/manual/en/function.str-replace.php
echo "$clinic_id_string<br>";
echo "$clinicname<br>";
echo "$log_text<br>";
这应该会提示您为什么它不起作用。
使用 preg_match 获取 str_replace
的诊所 ID 和模式$log_text = '%%clinicid=1%% clinic has <b>5</b> rooms.';
if (preg_match('/%%clinicid=(\d)%%/', $log_text, $m) !== false) {
$clean_clinicid = $m[1] ."\n";
$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;