Home  >  Article  >  Backend Development  >  Usage examples of common string processing functions in PHP [conversion, escaping, interception, comparison, search, reversal, cutting]

Usage examples of common string processing functions in PHP [conversion, escaping, interception, comparison, search, reversal, cutting]

高洛峰
高洛峰Original
2017-01-21 13:46:361096browse

This article analyzes the usage of common string processing functions in PHP. Share it with everyone for your reference, the details are as follows:

<?php
$s = "hello world";
//整理
echo &#39;trim(); ltrim(); rtrim()&#39;;
echo &#39;<br />&#39;;
echo &#39;长度为: &#39;.strlen($s);
echo &#39;<br />&#39;;
//大小写
echo &#39;首字母大写: &#39;.Ucfirst($s);
echo &#39;<br />&#39;;
echo &#39;每个单词首字母大写: &#39;.Ucwords($s);
echo &#39;<br />&#39;;
echo &#39;大写: &#39;. Strtoupper($s);
echo &#39;<br />&#39;;
echo &#39;小写: &#39;. Strtolower($s);
echo &#39;<br />&#39;;
// 转义字符串函数,存入数据库前使用
echo &#39;addslashes(); stripslashes();&#39;;
$s1 = &#39;"a"b&#39;;
echo &#39;<br />&#39;;
echo addslashes($s1);
echo &#39;<br />&#39;;
//截取
echo substr($s, 4, 4);
echo &#39;<br />&#39;;
$s2 = "hello world";
$s3 = "test";
//比较,相等返回0
echo strcmp($s, $s2) == 0 ? "相等":"不等";
echo &#39;<br />&#39;;
echo strcmp($s, $s3) == 0 ? "相等":"不等";
echo &#39;<br />&#39;;
//查找
echo strpos($s, &#39;o&#39;);
echo &#39;<br />&#39;;
echo strrpos($s, &#39;o&#39;);
//注意:如果查不到,则返回false == 0,所以要用"==="来检查if (XX === false);
echo &#39;<br />&#39;;
//反转
echo strrev($s);
echo &#39;<br />&#39;;
//切割
$arr = str_split($s);
$arr1 = str_split($s, 2);
$arr2 = explode(&#39; &#39;, $s);
var_dump($arr);
var_dump($arr1);
var_dump($arr2);
?>

I hope this article will be helpful to everyone in PHP programming design.

For more usage examples of common PHP string processing functions [conversion, escaping, interception, comparison, search, reversal, cutting], please pay attention to the PHP Chinese website for related articles!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn