av手机免费在线观看,国产女人在线视频,国产xxxx免费,捆绑调教一二三区,97影院最新理论片,色之久久综合,国产精品日韩欧美一区二区三区

php語(yǔ)言

php如何實(shí)現(xiàn)只替換一次或N次

時(shí)間:2025-04-27 21:00:08 php語(yǔ)言 我要投稿
  • 相關(guān)推薦

php如何實(shí)現(xiàn)只替換一次或N次

  介紹了php如何實(shí)現(xiàn)只替換一次或只替換N次,通過(guò)一個(gè)簡(jiǎn)單的例子引入主題,感性的朋友可以參考一下.

  我們都知道,在PHP里Strtr,strreplace等函數(shù)都可以用來(lái)替換,不過(guò)他們每次替換的時(shí)候都是全部替換,舉個(gè)例子:

  "abcabbc",這個(gè)字符串如果使用上邊的函數(shù)來(lái)把其中的b替換掉,那么他會(huì)全部替換掉,但是如果你想只替換一個(gè)或兩個(gè)怎么辦呢?看下邊的解決方法:

  這是個(gè)比較有點(diǎn)意思的問(wèn)題,正好之前也做過(guò)類(lèi)似的處理,當(dāng)時(shí)我是直接利用preg_replace實(shí)現(xiàn)的。

  mixed preg_replace ( mixed pattern, mixed replacement, mixed subject [, int limit] )

  在subject 中搜索pattern 模式的匹配項(xiàng)并替換為replacement。如果指定了 limit,則僅替換 limit 個(gè)匹配,如果省略 limit 或者其值為 -1,則所有的匹配項(xiàng)都會(huì)被替換。

  因?yàn)閜reg_replace的第四個(gè)參數(shù)可以實(shí)現(xiàn)替換次數(shù)的限制,所以這個(gè)問(wèn)題這樣處理很方便。但是在查看php.net上關(guān)于str_replace的函數(shù)評(píng)論后,從中居然也可以挑出幾個(gè)有代表性的函數(shù)來(lái)。

  方法一:str_replace_once

  思路首先是找到待替換的關(guān)鍵詞的位置,然后利用substr_replace函數(shù)直接替換之。

  <?php

  function str_replace_once($needle, $replace, $haystack) {

  // Looks for the first occurence of $needle in $haystack

  // and replaces it with $replace.

  $pos = strpos($haystack, $needle);

  if ($pos === false) {

  // Nothing found

  return $haystack;

  }

  return substr_replace($haystack, $replace, $pos, strlen($needle));

  }

  ?>

  方法二、str_replace_limit

  思路還是利用preg_replace,只不過(guò)它的參數(shù)更象preg_replace了,而且對(duì)某些特殊字符做了轉(zhuǎn)義處理,通用性更好。

  <?

  function str_replace_limit($search, $replace, $subject, $limit=-1) {

  // constructing mask(s)...

  if (is_array($search)) {

  foreach ($search as $k=>$v) {

  $search[$k] = '`' . preg_quote($search[$k],'`') . '`';

  }

  }

  else {

  $search = '`' . preg_quote($search,'`') . '`';

  }

  // replacement

  return preg_replace($search, $replace, $subject, $limit);

  }

  ?>

【php如何實(shí)現(xiàn)只替換一次或N次】相關(guān)文章:

如何使用php自定義函數(shù)實(shí)現(xiàn)漢字分割替換08-18

php自定義函數(shù)實(shí)現(xiàn)漢字分割替換06-01

PHP中多態(tài)如何實(shí)現(xiàn)09-04

php如何實(shí)現(xiàn)快速排序09-18

如何用PHP實(shí)現(xiàn)找回密碼11-11

php如何實(shí)現(xiàn)驗(yàn)證碼06-13

PHP弱類(lèi)型變量是如何實(shí)現(xiàn)的05-31

如何實(shí)現(xiàn)PHP圖片裁剪與縮放07-13

PHP中如何實(shí)現(xiàn)crontab代碼05-30