PHP使用 strpos、substr 函数 实现字符串替换

2018-10-28  本文已影响0人  竹本無心

<?php

// PHP使用 strpos、substr 函数 实现字符串替换

// strpos 某个字符串首次出现位置

// substr 字符截取

// 使用以上两个函数完成字符串替换

$a = 'he,llo,wo,rld';

// 输出 he;llo;wo;rld
echo ustr_replace($a, ',', ';');

function ustr_replace($str, $find, $replace, $start=0, $ustr=''){

  $inKey = strpos($str, $find, $start);

  if ($inKey) {

    $ustr .= substr($str, $start, $inKey-$start);

    $ustr .= $replace;

    return ustr_replace($str, $find, $replace, $inKey+1, $ustr);

  }

  $ustr .= substr($str, $start);

  return $ustr;

}

上一篇 下一篇

猜你喜欢

热点阅读