我从数据库查询中收到一个字符串,然后在将其放入CSV文件之前删除所有HTML标记,回车符和换行符.唯一的问题是,我无法找到一种方法来消除字符串之间多余的空白区域.
删除内部空白字符的最佳方法是什么?
jW.*_*jW. 281
不确定你想要什么,但这里有两种情况:
如果您只是处理whitespace可以使用的字符串的开头或结尾的多余部分trim(),ltrim()或者rtrim()将其删除.
如果要处理字符串中的额外空格,请考虑使用单个空格中preg_replace的多个空格.whitespaces " "*whitespace " "
例:
$foo = preg_replace('/\s+/', ' ', $foo);
Run Code Online (Sandbox Code Playgroud)
Cor*_*Dee 50
$str = str_replace(' ','',$str);
Run Code Online (Sandbox Code Playgroud)
或者,用下划线替换, 等等
Luk*_*kas 21
没有其他例子对我有用,所以我用过这个:
trim(preg_replace('/[\t\n\r\s]+/', ' ', $text_to_clean_up))
Run Code Online (Sandbox Code Playgroud)
这将所有标签,新行,双空格等替换为简单的1空格.
小智 9
如果您只想替换字符串中的多个空格,例如:"this string have lots of space . "
您希望答案是
"this string have lots of space",您可以使用以下解决方案:
$strng = "this string have lots of space . ";
$strng = trim(preg_replace('/\s+/',' ', $strng));
echo $strng;
Run Code Online (Sandbox Code Playgroud)
如果从用户输入[或其他不受信任的来源]获取有效负载,则使用preg_replace()会存在安全缺陷。PHP使用eval()执行正则表达式。如果未正确清理传入的字符串,则您的应用程序有遭受代码注入的风险。
在我自己的应用程序中,我没有烦恼清理输入(并且因为我只处理短字符串),而是制作了稍微占用处理器资源的函数,但这是安全的,因为它没有eval()任何东西。
function secureRip(string $str): string { /* Rips all whitespace securely. */
$arr = str_split($str, 1);
$retStr = '';
foreach ($arr as $char) {
$retStr .= trim($char);
}
return $retStr;
}
Run Code Online (Sandbox Code Playgroud)