php字符串函数 str类常见用法示例

2020-05-15 12:01:02于丽

%d = -123456789
%e = 1.234568e+8
%E = 1.234568E+8
%u = 123456789
%u = 18446744073586094827
%f = 123456789.000000
%F = 123456789.000000
%g = 1.23457e+8
%G = 1.23457E+8
%o = 726746425
%s = 123456789
%x = 75bcd15
%X = 75BCD15
%+d = +123456789
%+d = -123456789

substr_replace(mixed $string , mixed $replacement , mixed $start [, mixed $length ]);// 替换字符串的子串

$string:输入的字符串, $replacement:用来替换的字符串, $start:为正数时,从$string的start位置开始,为负数时,从$string的末尾开始,,,, $lenght:为正数时,表示被替换的子字符串的长度。为负数时,表示待替换的子字符串结尾处距离string末端的字符个数。
<?php
$var = 'ABCDEFGH:/MNRPQR/';
echo "Original: $var<hr />n";
 
/* 这两个例子使用 "bob" 替换整个 $var。*/
echo substr_replace($var, 'bob', 0) . "<br />n";
echo substr_replace($var, 'bob', 0, strlen($var)) . "<br />n";
 
/* 将 "bob" 插入到 $var 的开头处。*/
echo substr_replace($var, 'bob', 0, 0) . "<br />n";
 
/* 下面两个例子使用 "bob" 替换 $var 中的 "MNRPQR"。*/
echo substr_replace($var, 'bob', 10, -1) . "<br />n";
echo substr_replace($var, 'bob', -7, -1) . "<br />n";
 
/* 从 $var 中删除 "MNRPQR"。*/
echo substr_replace($var, '', 10, -1) . "<br />n";
?> 

strpos();//查找字符串首次出现的位置。

1、

<?php
// 忽视位置偏移量之前的字符进行查找
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, 不是 0
?> 

2、

<?php
$mystring = 'abc';
$findme  = 'a';
$pos = strpos($mystring, $findme);
 
// 使用 !== 操作符。使用 != 不能像我们期待的那样工作,
// 因为 'a' 的位置是 0。语句 (0 != false) 的结果是 false。
if ($pos !== false) {
   echo "The string '$findme' was found in the string '$mystring'";
     echo " and exists at position $pos";
} else {
   echo "The string '$findme' was not found in the string '$mystring'";
}
?> 

3、

<?php
$mystring = 'abc';
$findme  = 'a';
$pos = strpos($mystring, $findme);
 
// 注意这里使用的是 ===。简单的 == 不能像我们期待的那样工作,
// 因为 'a' 是第 0 位置上的(第一个)字符。
if ($pos === false) {
  echo "The string '$findme' was not found in the string '$mystring'";
} else {
  echo "The string '$findme' was found in the string '$mystring'";
  echo " and exists at position $pos";
}
?> 

preg_split($pet, $str);//通过一个正则表达式分隔字符串;

$keywords = preg_split("/[s,]+/", "hypertext language, programming");
print_r($keywords);

输出:

array(3) { 
[0]=>  string(9) "hypertext" 

相关文章 大家在看