首页 > 编程开发 > 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怎么去掉指定字符之后的内容

觉得上面的内容有用吗?快来点个赞吧!

点赞() 我要打赏

温馨提示 : 本站内容来自会员投稿以及互联网,所有源码及教程均为作者总结编辑,请大家在使用过程中提前做好备份,以免发生无法预知的错误,源码类教程请勿直接用于生产环境!

 可能感兴趣的文章