Laravel 10 Str::excerpt()传入含斜杠短语时触发preg_match异常
解决Laravel Str::excerpt()处理含斜杠短语时的preg_match报错问题
问题原因
Laravel的Str::excerpt()方法内部通过正则匹配短语位置时,使用/作为正则定界符,但调用preg_quote()时未传入该定界符作为第二个参数。这导致短语中的/不会被转义,直接出现在正则表达式中,提前终止了正则主体部分,后续字符被当作非法修饰符,最终抛出preg_match(): Unknown modifier 'y'异常。
解决方案
方案1:手动正确转义短语中的斜杠
注意PHP字符串的转义规则,确保传入的短语中/被正确转义为\/:
- 使用双引号字符串(自动解析转义序列):
Str::excerpt('This is m/y name', "m\/y", [ 'radius' => 3 ]);
- 使用单引号字符串(需手动转义反斜杠):
Str::excerpt('This is m/y name', 'm\\/y', [ 'radius' => 3 ]);
- 提前用
preg_quote()处理短语(指定正则定界符为/):
$escapedPhrase = preg_quote('m/y', '/'); Str::excerpt('This is m/y name', $escapedPhrase, [ 'radius' => 3 ]);
方案2:自定义摘要生成函数(规避正则)
如果不想依赖Laravel的Str::excerpt(),可以实现一个基于字符串查找的简单摘要生成逻辑,彻底避免正则问题:
function customExcerpt(string $text, string $phrase, int $radius = 3): string { $phraseLength = strlen($phrase); $position = strpos($text, $phrase); // 短语不存在时返回文本前半部分摘要 if ($position === false) { $excerpt = substr($text, 0, $radius * 2); return strlen($text) > $radius * 2 ? "{$excerpt}..." : $excerpt; } // 计算截取的起始和结束位置 $start = max(0, $position - $radius); $end = min(strlen($text), $position + $phraseLength + $radius); $excerpt = substr($text, $start, $end - $start); // 补充省略号 if ($start > 0) { $excerpt = "...{$excerpt}"; } if ($end < strlen($text)) { $excerpt = "{$excerpt}..."; } return $excerpt; } // 使用示例 echo customExcerpt('This is m/y name', 'm/y', 3); // 输出:...is m/y nam...
内容的提问来源于stack exchange,提问作者Clansi
相关产品推荐
相关产品推荐

