两种方法:1、用“substr_replace($str,"",strpos($str,"指定字符")+1)”语句,将指定字符位置后的内容替换为空字符;2、用“substr($str,0,strpos($str,"指定字符")+1)”语句。

本教程操作环境:windows7系统、PHP7.1版、DELL G3电脑

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;
?>

1.png

方法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;
?>

2.png


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