如何用PHP去除textarea中的HTML标签并解决多余空格问题
strip_tags仅会移除HTML标签,但原HTML中的换行、缩进、连续空格等空白字符会被完整保留,这就是textarea出现大量冗余空白的原因。以下是几种实用的解决方法:
方法1:正则替换连续空白字符
使用正则表达式将所有连续的空白字符(包括换行、空格、制表符)替换为单个空格,同时去除首尾空白:
$text = strip_tags($text); // 先去除首尾空白,再将连续空白替换为单个空格 $text = preg_replace('/\s+/', ' ', trim($text));
如果需要保留段落级别的换行(比如原HTML中的<p>或<br>对应的换行),可以先在移除标签前处理换行,再合并多余空格:
// 先将<br>标签替换为换行符 $text = preg_replace('/<br\s*\/?>/i', "\n", $text); // 将</p>标签替换为两个换行符(区分段落) $text = preg_replace('/<\/p>/i', "\n\n", $text); // 移除所有HTML标签 $text = strip_tags($text); // 仅合并连续空格,保留换行 $text = preg_replace('/[^\S\n]+/', ' ', trim($text));
方法2:针对WordPress内容的优化(如果你的数据来自WordPress REST API)
如果是处理WordPress返回的内容,可以先用wp_strip_all_tags函数(需在WordPress环境中),它会更智能地处理WordPress的内容格式:
// 第二个参数为true时保留换行 $text = wp_strip_all_tags($text, true); $text = preg_replace('/\s+/', ' ', trim($text));
若不在WordPress环境,可先移除短代码再处理:
// 移除WordPress短代码 $text = preg_replace('/\[.*?\]/', '', $text); $text = strip_tags($text); $text = preg_replace('/\s+/', ' ', trim($text));
修改后的完整代码示例
<?php foreach($data as $item){ if($yazi_id["id"]==$_GET["id"]){ $text = $item["content"]["rendered"]; $title = $item["title"]["rendered"]; break; } } // 处理文本内容 $text = strip_tags($text); $text = preg_replace('/\s+/', ' ', trim($text)); // 处理标题 $title = strip_tags($title); ?>
<html> <head> <title> Text</title> </head> <body> <div><?php echo "<b>".$title."</b>"; ?></div> <div class="form-outline"> <textarea class="form-control" id="textAreaExample1" rows="25" style="width:50%;" ><?php echo $text; ?></textarea> </div> </body> </html>
内容的提问来源于stack exchange,提问作者berre
相关产品推荐
相关产品推荐

