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怎么去掉指定字符之后的内容

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。