php入門教程(十九) php字串處理

來源:互聯網
上載者:User
  1. $str = "Hello world. It's a beautiful day.";
  2. print_r (explode(" ",$str));
  3. ?>
複製代碼

2、字串的串連 例子:

  1. //定義字串
  2. $str1 = "Hello World!";
  3. $str2 = "PHP !";
  4. //串連上面兩個字串 中間用空格分隔
  5. $str3 = $str1 . " " . $str2;
  6. //輸出串連後的字串
  7. echo $str3;
複製代碼

3、字串的截取 substr() , mb_substr例子:

  1. $str ="login.com";
  2. echo substr($str, 2); //gin.com
  3. echo substr($str, 2,3); //gin
  4. echo substr($str, -2); //om 負數從結尾開始取
  5. ?>
複製代碼

但是當你截取中文字串的時候很容易出現亂碼,因為一個漢字是兩個位元組,而一個英文字母是一個位元組。

解決辦法:2,mb_substr(),使用方法和substr相同,不過要開啟php.ini裡面extension=php_mbstring.dll擴充。

例子:

  1. echo mb_substr("int你好", 1,3,"UTF-8"); //nt你
  2. ?>
複製代碼

3. 字串尋找 strpos()定義和用法strpos() 函數返回字串在另一個字串中第一次出現的位置。如果沒有找到該字串,則返回false。

文法 strpos(string,find,start)

參數 描述 string 必需 規定被搜尋的字串find 必需 規定要尋找的字元。start 可選。規定開始搜尋的位置

例子:

  1. $string = '#11#22#33#44#55#66#77';
  2. $find = '#55';
  3. if(strpos($string,$find)===false){
  4. echo '沒有找到';
  5. }else{ // bbs.it-home.org
  6. echo '找到';
  7. }
  8. echo strpos($string,$find);
  9. ?>
複製代碼

4,字串替換 str_replace 例子:

  1. $replace_string = '你很壞,真的很壞';
  2. $replace_string_b = '很壞';
  3. $replace_string_ = str_replace($replace_string_b,'*',$replace_string,$i);
  4. echo $replace_string_ ;
  5. ?>
複製代碼

指定位置替換 substr_replace

  1. echo substr_replace("Hello world","php12",6); // Hello php12
  2. ?>
複製代碼

5,字串轉大小寫函數 將字串轉換成小寫strtolower(): 該函數將傳入的字串參數所有的字元都轉換成小寫,並以小定形式放回這個字串.例子:

  1. $str = "i love YOU";
  2. $str = strtolower($str);
  3. echo $str;
  4. ?>
複製代碼

輸出結果:i love YOU

將字元轉成大寫strtoupper(): 該函數的作用同strtolower函數相反,是將傳入的字元參數的字元全部轉換成大寫,並以大寫的形式返回這個字串.用法同strtolowe()一樣。

將字串首字元轉換成大寫usfilst(): 該函數的作用是將字串的第一個字元改成大寫,該函數返回首字元大寫的字串。用法同strtolowe()一樣。

將字串每個單詞的首字元轉換成大寫ucwords(): 該函數將傳入的字串的每個單詞的首字元變成大寫。如"hello world",經過該函數處理後,將返回"Hello Word"。用法同strtolowe()一樣。

>>> 查看更多 php入門教程 <<<

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.