
php只替换一次不重复【如何不替换<img>标签中的属性值,如alt,title】
现在的代码如下,如何在这个基础上添加条件,【不替换<img>标签中的属性,如alt,title】publicfunctionstr_replace_once($needl...
现在的代码如下,如何在这个基础上添加条件,【不替换<img>标签中的属性,如alt,title】
public function str_replace_once($needle,$replace,$haystack)
{
$pos = strpos($haystack, $needle);
if ($pos === false)
{
return $haystack;
}
return substr_replace($haystack, $replace, $pos, strlen($needle));
} 展开
public function str_replace_once($needle,$replace,$haystack)
{
$pos = strpos($haystack, $needle);
if ($pos === false)
{
return $haystack;
}
return substr_replace($haystack, $replace, $pos, strlen($needle));
} 展开
1个回答
展开全部
我试着写了一个,仅供参考:
function str_replace_once_new($needle,$replace,$haystack) {
$pattern = '/<img[^>]*>/is';
preg_match_all($pattern, $haystack, $matched);
if(empty($matched[0])){
$pos = strpos($haystack, $needle);
if ($pos === false) {
return $haystack;
}
return substr_replace($haystack, $replace, $pos, strlen($needle));
} else {
$arr = preg_split($pattern, $haystack);
$haystack_new = '';
$replace_time = 0;
foreach($arr as $key => $str){
$pos = strpos($str, $needle);
if ($pos === false || $replace_time > 0) {
$haystack_new .= $str;
} else {
$haystack_new .= substr_replace($str, $replace, $pos, strlen($needle));
$replace_time = 1;
}
if(isset($matched[0][$key])) $haystack_new .= $matched[0][$key];
}
return $haystack_new;
}
}
更多追问追答
追问
追答
那是因为你执行了多次这个替换函数,具体原因只有你自己找了。
如果你要做的是给关键字加链接,可以加个判断条件试一试:
function str_replace_once_new($needle,$replace,$haystack) {
//...
$pos = strpos($str, $needle);
if ($pos === false || $replace_time > 0 || strpos($str, $needle.'</a>') !== false) {
$haystack_new .= $str;
} else {
$haystack_new .= substr_replace($str, $replace, $pos, strlen($needle));
$replace_time = 1;
}
//...
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询