laravel查询结果是否已编码

laravel查询结果是否已编码

本文介绍了laravel查询结果是否已编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的laravel应用中,我正在尝试修剪从数据库中获得的结果. trim()不会删除字符串中的最后一个空格.

In my laravel app, I am trying to trim a result that I get from database. The trim() is not removing the last space in the string.

代码是这个

$institutes = Institute::all();

foreach ($institutes as $institute) {
    $str = $institute->name;
    $str = trim($str);  //doesn't remove the trailing space
    $len = strlen($str);
}

现在,首先,$str的长度比应该的长度大1.它应该是20,但以某种方式显示21.另一件事,根据我的输入,最后一个字符是space.

Now, first of all, the length of $str is 1 more than what it should be. It should be 20 but it somehow shows 21. Another thing, the last character is a space according to my input.

当我尝试打印last(21st)和倒数第二个(20th)字符时-最后一个字符(甚至不应该在那里)和倒数第二个字符应该是space.

When I try to print the last(21st) and second last(20th) characters - the last character(which should not even be there) and and the second last character which should be a space turns out to be something like this.

浏览器上的dot(作为倒数第二个字符)出现将近一秒钟,然后消失.现在,这是怎么回事?为什么会这样呢?

A dot on browser(as the second last character) appears for almost a second and then it disappears. Now, what is going on? Why is this happening?

请给我指示,否则我会全神贯注!

Please give me directions or else I am going to go out of my mind!

更新:

这是变量$str-

string(21) "Vidyalankar Classes "

推荐答案

我感觉到您所指的尾随空格是非utf8字符.

I have a feeling that the trailing space you are referring to is a non-utf8 character.

尝试删除所有无效字符,而不是修剪.

Try removing all invalid characters instead, rather than trimming.

foreach ($institutes as $institute) {
  $str = $institute->name;
  // be careful, try to double check, might also remove valid utf 8 characters like Chinese characters.
  $str = preg_replace('/[^(\x20-\x7F)]*/','', $str);
  $len = strlen($str);
}


请参阅修剪文档.


refer to trim documentation.

" " (ASCII 32 (0x20)), an ordinary space.
"\t" (ASCII 9 (0x09)), a tab.
"\n" (ASCII 10 (0x0A)), a new line (line feed).
"\r" (ASCII 13 (0x0D)), a carriage return.
"\0" (ASCII 0 (0x00)), the NUL-byte.
"\x0B" (ASCII 11 (0x0B)), a vertical tab.


您还可以尝试另一种方法,例如


You can also try another approach, like

$str = preg_replace('/[^A-Za-z0-9\. -]/','', $str);

// using trim, trims off invalid characters
$str = trim($str, "\x20..\x7F");

这篇关于laravel查询结果是否已编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 15:06