搜索
首页后端开发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 10, 2025 am 12:04 AM

TOOPTIMIZEPHPCODEFORDUSEMEMORYUSAGEAGEAGEAGEAGEAGEANDEXECUTITIEM,关注台词:1)USEREEREFERESCENCENCINCOPYINSTEADOFCOPYINGINATATASTRUCTURESTROUCTURESTOREDUCEMORYCONSUMPTION.2)杠杆phphppphpphp'sbuilt intimpunctionslikearray_mapforfunctionslikearray_mapforfforfforfforfasterapasterexecution.3)

PHP电子邮件:分步发送指南PHP电子邮件:分步发送指南May 09, 2025 am 12:14 AM

phpisusedforsendendemailsduetoitsignegrationwithservermailservicesand andexternalsmtpproviders,自动化notifications andMarketingCampaigns.1)设置设置yourphpenvironcormentswironmentswithaweberswithawebserverserverserverandphp,确保themailfunctionisenabled.2)useabasicscruct

如何通过PHP发送电子邮件:示例和代码如何通过PHP发送电子邮件:示例和代码May 09, 2025 am 12:13 AM

发送电子邮件的最佳方法是使用PHPMailer库。1)使用mail()函数简单但不可靠,可能导致邮件进入垃圾邮件或无法送达。2)PHPMailer提供更好的控制和可靠性,支持HTML邮件、附件和SMTP认证。3)确保正确配置SMTP设置并使用加密(如STARTTLS或SSL/TLS)以增强安全性。4)对于大量邮件,考虑使用邮件队列系统来优化性能。

高级PHP电子邮件:自定义标题和功能高级PHP电子邮件:自定义标题和功能May 09, 2025 am 12:13 AM

CustomHeadersheadersandAdvancedFeaturesInphpeMailenHanceFunctionalityAndreliability.1)CustomHeadersheadersheadersaddmetadatatatatataatafortrackingandCategorization.2)htmlemailsallowformattingandttinganditive.3)attachmentscanmentscanmentscanbesmentscanbestmentscanbesentscanbesentingslibrarieslibrarieslibrariesliblarikelikephpmailer.4)smtppapapairatienticationaltication enterticationallimpr

使用PHP和SMTP发送电子邮件的指南使用PHP和SMTP发送电子邮件的指南May 09, 2025 am 12:06 AM

使用PHP和SMTP发送邮件可以通过PHPMailer库实现。1)安装并配置PHPMailer,2)设置SMTP服务器细节,3)定义邮件内容,4)发送邮件并处理错误。使用此方法可以确保邮件的可靠性和安全性。

使用PHP发送电子邮件的最佳方法是什么?使用PHP发送电子邮件的最佳方法是什么?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

PHP中依赖注入的最佳实践PHP中依赖注入的最佳实践May 08, 2025 am 12:21 AM

使用依赖注入(DI)的原因是它促进了代码的松耦合、可测试性和可维护性。1)使用构造函数注入依赖,2)避免使用服务定位器,3)利用依赖注入容器管理依赖,4)通过注入依赖提高测试性,5)避免过度注入依赖,6)考虑DI对性能的影响。

PHP性能调整技巧和技巧PHP性能调整技巧和技巧May 08, 2025 am 12:20 AM

phperformancetuningiscialbecapeitenhancesspeedandeffice,whatevitalforwebapplications.1)cachingwithapcureduccureducesdatabaseloadprovesrovesponsemetimes.2)优化

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。