1 回答
TA贡献1836条经验 获得超13个赞
他的函数str_replace_first仅替换第一个匹配的字符串,并使用substr_count函数来了解字符串中还剩下多少特殊字符,我编写了这个简单的代码:
function str_replace_first($from, $to, $content){
$from = '/'.preg_quote($from, '/').'/';
return preg_replace($from, $to, $content, 1);
}
$str = "dog *cat* ping goat *pizza* cow *rabbit";
$Open_OR_Closed_Tag = false; // this for to know what tag should put
while (substr_count($str, '*') > 1 || $Open_OR_Closed_Tag) {
if ($Open_OR_Closed_Tag) {
$str = str_replace_first("*", "</strong>", $str);
$Open_OR_Closed_Tag = false;
} else {
$str = str_replace_first("*", "<strong>", $str);
$Open_OR_Closed_Tag = true;
}
}
echo $str; // dog <strong>cat</strong> ping goat <strong>pizza</strong> cow rabbit*
- 1 回答
- 0 关注
- 99 浏览
添加回答
举报