php怎么去掉指定字符之后的内容

来自:互联网
时间:2022-05-27
阅读:

php去掉指定字符之后内容的两种方法

方法1:利用strpos()和substr_replace() 函数

  • 利用strpos()找到指定字符的位置,例字符d

  • 使用substr_replace()将指定字符后的内容替换为空字符

substr_replace()用于从指定位置开始替换字符,而我们需要从指定字符后开始替换,因此开始替换的位置值为“指定字符的位置+1”。

<?php
header('content-type:text/html;charset=utf-8');   
$str = "abcdefg";
echo "原字符串:".$str."<br>";
$index = strpos($str,"d");
$res = substr_replace($str,"",$index+1);
echo "去除字符d后的内容:".$res;
?>

php怎么去掉指定字符之后的内容

方法2:利用strpos()和substr()函数

  • 使用strpos函数找到指定字符的位置,例字符e

  • 使用substr函数从字符串的开头截取至指定字符的位置

<?php
header('content-type:text/html;charset=utf-8');   
$str = "abcdefg";
echo "原字符串:".$str."<br>";
$index = strpos($str,"e");
$res = substr($str,0,$index+1);
echo "去除字符e后的内容:".$res;
?>

php怎么去掉指定字符之后的内容

返回顶部
顶部