天天看點

字元串常用函數

nl2br

功能:化換行符為<br>

<?php

$str = "cat isn't \n dog";

$result = nl2br($str);

echo $result;

rtrim

功能:清除右邊的空白

<?php

$str = "Hello world ";

echo strlen($str)."<br>";

$result = rtrim($str);

echo strlen($result);

strip_tags

功能:清除字元串中html和php的标記

<?php

$str = "<font color = 'red'>Hello world</font>";

$result = strip_tags($str);

echo $result;

strtolower 與 strtoupper

功能:轉換成大小寫

<?php

$str = "Hello World!";

$result = strtolower($str);

echo $result."<br>";

$result = strtoupper($str);

echo $result;

trim

功能:去除首尾空格

<?php

$str = " Hello World! ";

$result = trim($str);

echo $str."<br>";

echo $result."<br>";

echo strlen($str)."<br>";

echo strlen($result);

str_ireplace

功能:替換

<?php

$str = "zhang san";

$result = str_ireplace("zhang","li",$str);

echo $str."<br>";

echo $result;

str_repeat

功能:将一個字元串重複多遍

<?php

$str = "Hello jiqing!";

$result = str_repeat($str,4);

echo $str."<br>";

echo $result;

str_replace

功能:區分大小寫的替換

<?php

$str = "hello jiqing!";

$result1 = str_ireplace("Hello","Hi",$str); //不區分大小寫

$result2 = str_replace("Hello","Hi",$str); //區分大小寫

echo $str."<br>";

echo $result1."<br>";

echo $result2."<br>";

str_word_count

功能:傳回字元串中單詞的個數

<?php

$str = "hello jiqing a!";

$result1 = str_word_count($str); //傳回個數

$result2 = str_word_count($str,1); //傳回數組

echo $str."<br>";

echo $result1."<br>";

print_r($result2);

strlen

功能:傳回字元串長度

<?php

$str = "hello jiqing a!";

$result = strlen($str);

echo $result;

substr_count

功能:計算一個字元串在另一個字元串中的個數

<?php

$str = "hello jiqing ,hello jim!";

$result = substr_count($str,"hello");

echo $result;

substr_replace

功能:從某個位置開始替換

<?php

$str = "hello jiqing ,hello jim!";

$result = substr_replace($str,"zhangsan",6);

echo $result."<br>";

$result = substr_replace($str,"zhangsan",6,6);//從某個位置替換,替換幾個字元串

echo $result;

substr

功能:擷取子字元串

<?php

$str = "abcdef";

$result = substr($str,0,1); //從第0個開始,擷取1個

echo $result."<br>";

$result = substr($str,0,-1);//從第0個開始,擷取到除了最後一個的字元串

echo $result."<br>";

$result = substr($str,2,-1);//從第2個開始,擷取到除了最後一個的字元串

echo $result."<br>";

$result = substr($str,-3,-1);//從第-3個開始,擷取到除了最後一個的字元串

echo $result."<br>";

$result = substr($str,-3,1);//從第-3個開始,擷取到除了最後一個的字元串

echo $result."<br>";

implode

功能:将數組轉化為字元串

<?php

$array = array("2016","6","3");

$date = implode("/",$array);

echo $date;

md5

功能:對字元串進行md5加密

<?php

$str = "Hello world";

$result = md5($str);

echo $result;