You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP技术问询:获取重复字符前字符串及变量最后逗号后内容

PHP字符串处理实用方案

嘿,针对你问的两个PHP字符串问题,我整理了几个实用的解决办法,都是日常开发里常用的:

问题1:如何获取某重复出现的字符之前的字符串内容?

首先得明确你要的是第一次出现该字符之前的内容,还是最后一次出现该字符之前的内容,两种场景的处理方式不一样:

场景1:取第一次出现重复字符前的内容

比如你的字符串是"apple,banana,orange",想拿到第一个逗号前的"apple",有两种简单方法:

  • 用strstr()函数(第三个参数传true会返回匹配字符之前的内容):
$str = "apple,banana,orange";
$targetChar = ",";
$result = strstr($str, $targetChar, true);
// 输出结果:apple
  • 或者用strpos()找到字符位置,再用substr()截取:
$str = "apple,banana,orange";
$targetChar = ",";
$charPosition = strpos($str, $targetChar);
// 一定要判断字符是否存在,避免报错
if ($charPosition !== false) {
    $result = substr($str, 0, $charPosition);
} else {
    // 如果目标字符没出现,就返回原字符串
    $result = $str;
}
// 输出结果:apple

场景2:取最后一次出现重复字符前的内容

还是用上面的例子,想拿到最后一个逗号前的"apple,banana",用strrpos()(找字符最后一次出现的位置)配合substr()就行:

$str = "apple,banana,orange";
$targetChar = ",";
$lastCharPosition = strrpos($str, $targetChar);
if ($lastCharPosition !== false) {
    $result = substr($str, 0, $lastCharPosition);
} else {
    $result = $str;
}
// 输出结果:apple,banana

问题2:处理变量$valt = ",book,farm,chop,cook"的两个需求

你的两个小需求,我分别给你写了实现代码:

需求1:获取最后一个逗号右侧的内容(也就是"cook")

这里有两种靠谱的方法:

  • 用strrchr()直接抓取最后一个逗号之后的内容,再用ltrim()去掉前面多余的逗号:
$valt = ",book,farm,chop,cook";
$result = ltrim(strrchr($valt, ","), ",");
// 输出结果:cook
  • 或者用strrpos()找到最后一个逗号的位置,再用substr()截取后面的内容:
$valt = ",book,farm,chop,cook";
$lastCommaPos = strrpos($valt, ",");
if ($lastCommaPos !== false) {
    $result = substr($valt, $lastCommaPos + 1);
} else {
    $result = $valt;
}
// 输出结果:cook

需求2:从右侧截取至第一个逗号之前的内容(也就是",book,farm,chop")

其实就是取最后一个逗号之前的所有内容,用strrpos()配合substr()就能实现:

$valt = ",book,farm,chop,cook";
$lastCommaPos = strrpos($valt, ",");
if ($lastCommaPos !== false) {
    $result = substr($valt, 0, $lastCommaPos);
} else {
    $result = $valt;
}
// 输出结果:,book,farm,chop

内容的提问来源于stack exchange,提问作者flochristos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:49:18