PHP实现从指定单词开始删除后续全部字符串的技术问询
PHP 删除指定单词及后续所有内容的解决方案
下面提供两种实用实现方式,适配你的需求场景:
方法一:字符串定位截取(基础版)
通过定位目标单词的起始位置,截取该位置之前的内容,适合纯文本或简单HTML场景:
$originalText = 'Lorem Ipsum is simply the dummy text of printers and text files. Lorem Ipsum has been the industry\'s standard dummy text since the 1500s, when an <strong>unknown</strong> printer used a gallery of type and mixed it up in such a way that he managed to make a specimen textbook. Not only did it survive 500 years, but it also entered as a text of'; $targetWord = 'unknown'; // 查找目标单词的首次出现位置 $pos = strpos($originalText, $targetWord); // 若找到则截取前面的内容,否则返回原文本 $result = $pos !== false ? substr($originalText, 0, $pos) : $originalText; // 可选:清理末尾残留的未闭合HTML标签(适配你的示例需求) $result = preg_replace('/<[^>]*$/', '', $result); echo $result;
方法二:正则表达式替换(灵活版)
适合需要更精准匹配的场景(如忽略大小写、匹配完整单词),直接替换目标单词及后续所有内容:
$originalText = 'Lorem Ipsum is simply the dummy text of printers and text files. Lorem Ipsum has been the industry\'s standard dummy text since the 1500s, when an <strong>unknown</strong> printer used a gallery of type and mixed it up in such a way that he managed to make a specimen textbook. Not only did it survive 500 years, but it also entered as a text of'; $targetWord = 'unknown'; // 转义目标单词的特殊字符,避免正则语法冲突 $safeWord = preg_quote($targetWord, '/'); // 匹配从目标单词到文本末尾的所有内容并替换为空 $result = preg_replace("/{$safeWord}.*/s", '', $originalText); // 可选:清理末尾残留的未闭合HTML标签 $result = preg_replace('/<[^>]*$/', '', $result); echo $result;
两种方法最终输出结果均为:
Lorem Ipsum is simply the dummy text of printers and text files. Lorem Ipsum has been the industry's standard dummy text since the 1500s, when an
内容的提问来源于stack exchange,提问作者Kezman10
相关产品推荐
相关产品推荐

