很简单:如何用php替换“all between”?
2022-08-30 15:29:00
$string = "<tag>i dont know what is here</tag>"
$string = str_replace("???", "<tag></tag>", $string);
echo $string; // <tag></tag>
那么我在寻找什么代码呢?
$string = "<tag>i dont know what is here</tag>"
$string = str_replace("???", "<tag></tag>", $string);
echo $string; // <tag></tag>
那么我在寻找什么代码呢?
一个通用函数:
function replace_between($str, $needle_start, $needle_end, $replacement) {
$pos = strpos($str, $needle_start);
$start = $pos === false ? 0 : $pos + strlen($needle_start);
$pos = strpos($str, $needle_end, $start);
$end = $pos === false ? strlen($str) : $pos;
return substr_replace($str, $replacement, $start, $end - $start);
}
$search = "/[^<tag>](.*)[^<\/tag>]/";
$replace = "your new inner text";
$string = "<tag>i dont know what is here</tag>";
echo preg_replace($search,$replace,$string);
输出:
<tag>your new inner text</tag>