[英]Trim with PHP
I have a sentence like this.我有这样一句话。
1 2 3 4
As you see, in between 1 2 and 3 text, there are extra spaces.如您所见,在 1 2 和 3 文本之间,有额外的空格。 I want the output with only one space between them.
我想要 output 之间只有一个空格。 so my output will be
1 2 3 4
.所以我的 output 将是
1 2 3 4
。
If I use trim, it can only remove white space, but not that
如果我使用修剪,它只能删除空格,但不能删除
How can I use PHP trim function to get the output like this?我怎样才能使用 PHP 修剪 function 得到这样的 output?
Found this at php.net, works great: 在php.net上找到这个,效果很好:
$myHTML = " abc";
$converted = strtr($myHTML, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));
trim($converted, chr(0xC2).chr(0xA0));
Source: http://php.net/manual/en/function.trim.php#98812 资料来源: http : //php.net/manual/en/function.trim.php#98812
$str = "1 $nbsp; 2 3 4";
$new_str = str_replace(" ", '', $str);
A more inclusive answer for those who want to just do a trim: 对于那些想要修剪的人来说,这是一个更具包容性的答案:
$str = trim($str, " \t\n\r\0\x0B\xC2\xA0");
Same trim handling html entities: 相同的修剪处理html实体:
$str = trim(html_entity_decode($str), " \t\n\r\0\x0B\xC2\xA0");
This html_entity_decode and trim interaction is outlined in the PHP docs here: http://php.net/manual/en/function.html-entity-decode.php#refsect1-function.html-entity-decode-notes 这里的html_entity_decode和trim交互概述在PHP文档中: http : //php.net/manual/en/function.html-entity-decode.php#refsect1-function.html-entity-decode-notes
$str = " abc ";
echo trim($str, "\xC2\xA0"); //abc
if your string actually has " ", 如果你的字符串实际上有“”,
$str="1 2 3 4";
$s = str_replace(" ","",$str);
print $s;
echo str_replace ( " ", "", "1 2 3 4" );
只记得你需要回显str_replace的结果,你也不需要担心空格,浏览器只会显示一个空格。
A little late to answer but hopefully might help someone else. 回答有点迟,但希望可以帮助别人。 The most important while extracting content from html is to use utf8_decode() in php.
从html中提取内容时最重要的是在php中使用utf8_decode() 。 Then all other string operations become a breeze.
然后所有其他字符串操作变得轻而易举。 Even foreign characters can be replaced by directly copy pasting characters from browser into the php code.
甚至可以通过将浏览器中的粘贴字符直接复制到php代码来替换外来字符。 The following function replaces
以下功能取代
with a space. 有空间。 Then all extra white spaces are replaced with a single white space using
preg_replace()
. 然后使用
preg_replace()
将所有额外的空格替换为单个空格。 Leading and trailing white spaces are removed in the end. 最后删除了前导和尾随空格。
function clean($str)
{
$str = utf8_decode($str);
$str = str_replace(" ", " ", $str);
$str = preg_replace('/\s+/', ' ',$str);
$str = trim($str);
return $str;
}
$html = "1 $nbsp; 2 3 4";
$output = clean($html);
echo $output;
1 2 3 4
1 2 3 4
This did the job for me:这为我完成了工作:
preg_replace('~\x{00a0}~siu',' ',$content); preg_replace('~\x{00a0}~siu',' ',$content);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.