国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 網站 > 建站經驗 > 正文

php substr_replace替換字符串教程分享

2024-04-25 20:36:28
字體:
來源:轉載
供稿:網友

substr_replace與str_replace有一點像就是直接把字符串替換一部份了,下面小編來給各位同學介紹一下操作方法。

substr_replace() 函數把字符串的一部分替換為另一個字符串。
用法:


substr_replace(string,replacement,start,length)

注意當字符串包含中文時,不經過特殊處理會出現亂碼,代碼如下:

<?php

$string1="123456789";

echo substr_replace($string1,'###',0);

//### http://www.bcty365.com

echo substr_replace($string1,'###',5);

//12345###

echo substr_replace($string1,'###',0,0);

//###123456789

echo substr_replace($string1,'###',8,-2);

//12345678###9

echo substr_replace($string1,'###',-6,-1);
//123###9

echo "n";

echo substr_replace($string1,'###',-1);

//123###9

echo "n";

echo substr_replace($string1,'###',1,-1);

//1###9

echo substr_replace($string1,'###',1,1);

//1###3456789

?>

例2代碼如下:

<?php

$var = 'ABCDEFGH:/MNRPQR/';

echo "Original: $var<hr />n";

/* These two examples replace all of $var with 'bob'.
*/http://www.bcty365.com

echo substr_replace($var, 'bob', 0) . "<br />n";

echo substr_replace($var, 'bob', 0, strlen($var)) . "<br />n";

/* Insert 'bob' right at the beginning of $var. */

echo substr_replace($var, 'bob', 0, 0) . "<br />n";

/* These next two replace 'MNRPQR' in $var with 'bob'. */

echo substr_replace($var, 'bob', 10, -1) . "<br />n";

echo substr_replace($var, 'bob', -7, -1) . "<br />n";

/* Delete 'MNRPQR' from $var. */

echo substr_replace($var, '', 10, -1) . "<br />n";

?>

將過長的字符串用省略號代替一部分,下面的程序可以將過長的字符串保留首尾,中間用省略號代替,代碼如下:

<?php

$longString = 'abcdefghijklmnopqrstuvwxyz0123456789z.jpg';

$separator = '...';

$separatorlength = strlen($separator) ;

// 需要保留的字符串

$maxlength = 25 - $separatorlength;

// 從一半的長度開始http://www.bcty365.com
$start = $maxlength / 2 ;

// 計算偏移量

$trunc = strlen($longString) - $maxlength;

echo substr_replace($longString, $separator, $start, $trunc);

//prints "abcdefghij...56789z.jpg"

?>

//程序運行結果:

//abcdefghijk...456789z.jpg

Program List:將多出的字符用省略號代替,代碼如下:

<?php

function truncate($text,$numb)

{

$text = html_entity_decode($text, ENT_QUOTES);

if (strlen($text) > $numb)

{

$text = substr($text, 0, $numb);

$text = substr($text,0,strrpos($text," "));

//This strips the full stop:

if ((substr($text, -1)) == ".")

{

$text = substr($text,0,(strrpos($text,".")));

}

$etc = "...";

$text = $text.$etc;

}

$text = htmlentities($text, ENT_QUOTES);

return $text;

}

//Call function

$text = 'welcome to nowamagic, welcome to nowamagic, welcome to nowamagic';

$result = truncate($text, 35);

echo $result;

?>

好了你大概會知道此函數的作用了.

 

 

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 澳门| 隆尧县| 曲沃县| 富裕县| 沙湾县| 永平县| 东台市| 营山县| 宾阳县| 兴安县| 政和县| 文水县| 施秉县| 嘉义县| 福清市| 平乡县| 涪陵区| 灵寿县| 武冈市| 咸阳市| 调兵山市| 白河县| 哈密市| 宁远县| 邵武市| 桂平市| 林甸县| 东兴市| 威信县| 岐山县| 呼伦贝尔市| 西贡区| 玛纳斯县| 枣强县| 玉屏| 积石山| 平塘县| 三穗县| 浮梁县| 垫江县| 威信县|