찾다
백엔드 개발PHP 튜토리얼 PHP开发札记系列(二)-字符串使用

PHP开发笔记系列(二)-字符串使用
   
    经过了《PHP开发笔记系列(一)-PDO使用》,今天开了关于PHP开发中字符串的处理,《PHP开发笔记系列(二)-字符串使用》,形成《PHP开发笔记系列》的第二篇。

    字符串是任何开发语言都必须处理的,在PHP中字符串可以使用单引号(')或双引号(")进行定义。那单引号和双引号不同之处在哪?那就是双引号中的变量会被变量值替换,而单引号中的内容将原样输出。下面将日常程序开发中会碰到的字符串处理场景整理。


1. 以数组形式访问字符串(strlen)

file:str-lengh.php
url:http://localhost:88/str/str-lengh.php
<?php $word = 'Hello, Ryan!';
    echo "String($word)'s length: ".strlen($word)."<br/>";
    
    // for循环访问数组
    //for($i=0; $i<strlen echo></strlen>";
    //}
    
    // while循环访问数组
    $i=0;
    while($i<strlen echo></strlen>";
         $i++
    }
?>

2. 去除文本中的所有HTML标记(strip_tags)
file:str-strip-tags.php
url:http://localhost:88/str/str-strip-tags.php
<?php // 字符串中的所有html标签都闭合
    $text = "<h1 id="hello-world-h-hello-world">hello world!<h1 id="hello-world">hello world!</h1><h1 id="hello-world">hello world!</h1>";
    
    // 输出原始的字符串内容
    echo "Original Text:";
    echo $text."<br>";
    
    // 去除所有html标签后进行输出
    echo "Destination Text(After strip_tags)"."<br>";
    echo strip_tags($text)."<br>";

    // 字符串中的html标签不闭合
    $text = "<h1>hello world!";
    
    // 去除所有html标签后进行输出
    echo "Original Text:";
    echo $text."<br>";
    
    // 去除所有html标签后进行输出
    echo "Destination Text(After strip_tags)"."<br>";
    echo strip_tags($text)."<br>";
?>
</h1>

    备注:如果$text的值是

hello world!,少了

,那么

将不会被strip_tags函数去除,从而影响后面的格式输出,使后续的所有输出都有h1标题的样式。



3. 转义html实体(rawurlencode)
file:str-entities.php
url:http://localhost:88/str/str-entities.php
<?php $text = "hello & world!";
    
    echo $text."<br/>";
    
    echo rawurlencode($text)."<br>";
?>


4. 强制文本折行显示(wordwrap)
    wordwrap函数可以按照指定的字符串折行长度,将长文本进行折行。
file:str-wordwrap.php
url:http://localhost:88/str/str-wordwrap.php
<?php $text = "This document covers the JavaTM 2 Platform Standard Edition 5.0 Development Kit (JDK 5.0). Its external version number is 5.0 and internal version number is 1.5.0. For information on a feature of the JDK, click on its component in the diagram below.";
    
    echo "Original text:"."<br/>";
    echo $text."<br>";
    
    echo $text."<hr>";
    
    echo "Destination text(after wrap):"."<br>";
    echo wordwrap($text, 50, "<br>")."<br>";
?>


5. 字符串定位与替换(strpos、str_replace)
    字符串定位使用strpos函数,该函数返回一个字符串在另一个字符串出现的第一个位置,类似于JAVA中String类的indexOf()方法的作用:
file:str-strpos.php
url:http://localhost:88/str/str-strpos.php
<?php $text = "hello world!";
    
    echo strpos($text, "e");  
?>


    字符串替换使用str_replace函数,该函数替换部分字符串中的文本,类似于JAVA中String类的replace()方法的作用:
file:str-strreplace.php
url:http://localhost:88/str/str-strreplace.php
<?php $text = "This document covers the JavaTM 2 Platform Standard Edition 5.0 Development Kit (JDK 5.0). Its external version number is 5.0 and internal version number is 1.5.0. For information on a feature of the JDK, click on its component in the diagram below.";
   
    echo "Original text:"."<br/>";
    echo $text."<br>";
    
    echo "<hr>";
    
    echo "Destination text(replace):"."<br>";
    echo str_replace(" ", "__", $text)."<br>";    
?>


6. 字符串比较(substr_compare)
    字符串比较可用于比较两个字符串间的大小,类似于JAVA中String的compare方法,如果返回值>0,代表第一个字符串比第二个大,反之第二个比第一个大,若为0,表示相等。
file:str-compare.php
url:http://localhost:88/file/str-compare.php
<?php $main_str = 'hello world';
    $str = 'hello world, Ryan!';
    echo substr_compare($main_str, $str, 0);
?>


7. 字符串截取(substr)
    字符串截取可用于从字符串的指定位置截取指定长度的字串,用于子串值抽取很方便。
file:str-sub.php
url:http://localhost:88/file/str-sub.php
<?php $str = 'hello world,today is sunday!';
    $start = strpos($str, ',');
    $newStr = substr($str, $start+1);

    echo 'Original String: '.$str.'<br/>';
    echo 'Destination String: '.$newStr.'<br>';
?>


8. 统计子串出现次数(substr_count)
    统计子串在父串中出现的次数,可以使用substr_count函数。
file:str-count.php
url:http://localhost:88/file/str-count.php
<?php $str = 'abcdefgacef';
    
    echo substr_count($str, 'a');
?>


9. 字符串分拆与拼装(explode、implode)
    字符串分拆可将一个字符串按照一个指定分隔符拆分成数组,类似于JAVA中String类的spilt()方法的作用。字符串组装时将字符串数组按照一个分隔符将数组中的数据进行拼装,形成一个新字符串。
file:str-explode-implode.php
url:http://localhost:88/str/str-explode-implode.php
<?php $text = "This document covers the JavaTM 2 Platform Standard Edition 5.0 Development Kit (JDK 5.0). Its external version number is 5.0 and internal version number is 1.5.0. For information on a feature of the JDK, click on its component in the diagram below.";
   
    echo "Original text:"."<br/>";
    echo $text."<br>";
    
    echo "<hr>";
    
    $sentenses = explode(". ", $text);
    echo "Destination text(explode):"."<br>";
    foreach ($sentenses as $sentense){
        echo $sentense."<br>";
    }
    
    echo "<hr>";
    
    $newText= implode($sentenses, ". ");
    
    echo "Destination text(implode):"."<br>";
    echo $newText."<br>";    
?>


10. 去除字符串的前后空格(trim)
file:str-trim.php
url:http://localhost:88/str/str-trim.php
<?php $text = "   hello world!  ";
    
    echo "Original text:"."<br/>";
    echo strlen($text)."<br>";
    
    echo "<hr>";
    
    echo "Destination text(trim):"."<br>";
    echo strlen(trim($text))."<br>"; 
?>


11. 格式化输出(printf)
    格式化输出使用printf函数或sprintf函数,类似于C语言中的printf函数的作用:
file:str-printf.php
url:http://localhost:88/str/str-printf.php
<?php $format = 'hello, %2$s, userNo: %1$s';
    $who = 'Ryan';
    $no = '10';
    
    echo printf($format, $no, $who);    
?>


    本文地址:http://ryan-d.iteye.com/blog/1543225
성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
PHP를 사용하여 이메일을 보내는 가장 좋은 방법은 무엇입니까?PHP를 사용하여 이메일을 보내는 가장 좋은 방법은 무엇입니까?May 08, 2025 am 12:21 AM

TheBesteptroachForendingeMailsInphPisusingThephPmailerlibraryDuetoitsReliability, featurerichness 및 reaseofuse.phpmailersupportssmtp, proversDetailErrorHandling, supportSattachments, andenhancessecurity.foroptimalu

PHP의 종속성 주입을위한 모범 사례PHP의 종속성 주입을위한 모범 사례May 08, 2025 am 12:21 AM

의존성 주입 (DI)을 사용하는 이유는 코드의 느슨한 커플 링, 테스트 가능성 및 유지 관리 가능성을 촉진하기 때문입니다. 1) 생성자를 사용하여 종속성을 주입하고, 2) 서비스 로케이터 사용을 피하고, 3) 종속성 주입 컨테이너를 사용하여 종속성을 관리하고, 4) 주입 종속성을 통한 테스트 가능성을 향상 시키십시오.

PHP 성능 튜닝 팁 및 요령PHP 성능 튜닝 팁 및 요령May 08, 2025 am 12:20 AM

phpperformancetuningiscrucialbecauseitenhancesspeedandefficies, thearevitalforwebapplications.1) cachingsdatabaseloadandimprovesResponsetimes.2) 최적화 된 databasequerieseiesecessarycolumnsingpeedsupedsupeveval.

PHP 이메일 보안 : 이메일 보내기 모범 사례PHP 이메일 보안 : 이메일 보내기 모범 사례May 08, 2025 am 12:16 AM

theBestPracticesForendingEmailsSecurelyPinphPinclude : 1) usingecureconfigurations와 whithsmtpandstarttlSencryption, 2) 검증 및 inputSpreverventInseMeStacks, 3) 암호화에 대한 암호화와 비도시를 확인합니다

성능을 위해 PHP 응용 프로그램을 어떻게 최적화합니까?성능을 위해 PHP 응용 프로그램을 어떻게 최적화합니까?May 08, 2025 am 12:08 AM

tooptimizephPapplicationsperperperperperperperperperferferferferferferferferferferperferferperferperperferferfercations.1) ubsicationScachingwithApcuTeDucedAtaFetchTimes.2) 최적화 된 ABASEABASES.3)

PHP의 종속성 주입이란 무엇입니까?PHP의 종속성 주입이란 무엇입니까?May 07, 2025 pm 03:09 PM

expendencyInphpisaDesignpatternpattern thatenhances-flexibility, testability 및 maintainabilitable externaldenciestoclasses.itallowsforloosecoupling, easiertesting throughmocking 및 modulardesign, berrequirecarefultructuringtoavoid-inje

최고의 PHP 성능 최적화 기술최고의 PHP 성능 최적화 기술May 07, 2025 pm 03:05 PM

PHP 성능 최적화는 다음 단계를 통해 달성 할 수 있습니다. 1) 스크립트 상단에 require_once 또는 include_once를 사용하여 파일로드 수를 줄입니다. 2) 데이터베이스 쿼리 수를 줄이기 위해 전처리 문 및 배치 처리를 사용하십시오. 3) Opcode 캐시에 대한 Opcache 구성; 4) PHP-FPM 최적화 프로세스 관리를 활성화하고 구성합니다. 5) CDN을 사용하여 정적 자원을 배포합니다. 6) 코드 성능 분석을 위해 Xdebug 또는 Blackfire를 사용하십시오. 7) 배열과 같은 효율적인 데이터 구조를 선택하십시오. 8) 최적화 실행을위한 모듈 식 코드를 작성하십시오.

PHP 성능 최적화 : Opcode 캐싱 사용PHP 성능 최적화 : Opcode 캐싱 사용May 07, 2025 pm 02:49 PM

opCodeCachingsIntIficInlyIntImeRimproveSphpperformanceCachingCompileDCode, retingServerLoadandResponsEtimes.1) itStoresCompyledPhpCodeInMemory, BYPASSINGPARSINGCOMPILING.2) UseOpCacheSettingParametersInphP.Ini, likeMoryConsAncme AD

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기