使用 strpos() 查找分隔符位置,再结合 substr() 截取该位置之前的内容即可。具体做法是先获取分隔符的索引,判断其是否存在(不等于 false),然后调用 substr($string, 0, $pos) 提取子串。如果分隔符不存在,通常返回原字符串或空值,需根据业务逻辑处理。

strpos 找不到分隔符时如何处理
当 strpos() 未找到指定字符时,会返回布尔值 false。此时若直接将其作为长度参数传给 substr(),在 PHP 8.0+ 中会抛出 TypeError,而在旧版本中可能产生意外结果。因此必须在调用 substr() 前检查返回值是否为 false。若未找到分隔符,可根据需求选择返回完整字符串、空字符串或抛出异常。

使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
<?php
$string = "user@example.com";
$delimiter = "@";
$pos = strpos($string, $delimiter);
if ($pos !== false) {
$result = substr($string, 0, $pos);
echo "Found: " . $result;
} else {
echo "Delimiter not found";
}
?>
substr 截取边界情况验证
当分隔符位于字符串开头时,strpos() 返回 0,substr($string, 0, 0) 将返回空字符串。这是符合预期的行为,因为分隔符前没有内容。同样,如果分隔符是最后一个字符,substr() 会截取到倒数第二个字符。这些边界情况在实际解析路径、邮箱或文件名时非常常见,必须确保代码能正确处理零长度截取的场景。
立即学习“PHP免费学习笔记(深入)”;

<?php // 测试分隔符在开头的情况 $string1 = "/path/to/file"; $pos1 = strpos($string1, "/"); $result1 = ($pos1 !== false) ? substr($string1, 0, $pos1) : $string1; echo "Result 1: '" . $result1 . "'\n"; // Output: '' // 测试分隔符在末尾的情况 $string2 = "filename."; $pos2 = strpos($string2, "."); $result2 = ($pos2 !== false) ? substr($string2, 0, $pos2) : $string2; echo "Result 2: '" . $result2 . "'\n"; // Output: 'filename' ?>


















