如何从字符串中过滤掉不可见的字符

时间:2018-04-02 12:20:39

标签: php string laravel-5.3

我已经从粘贴到txt的网页上手动复制了一些项目,然后将其存储到数据库中。现在我错过的是隐形字符。

当我使用substr($ word,0,x)中的不同值检索每个单词的第一个字符时,它会显示不可见字符的存在。

php code -

substr($word,0,1)
string-'data structures and algorithms'
output-'SA'
expected-'DSA'

string-'Web Development'
output-'WD'

substr($word,0,2)
string-'data structures and algorithms'
output-'DSTAL'
expected-'DASTAL'

string-'Web Development'
output-'WEDE'

输出 -

valgrind --tool=memcheck --track-origins=yes <program_path>

4 个答案:

答案 0 :(得分:0)

你快到了:

scrollView.post(new Runnable() { 
        public void run() { 
             scrollView.fullScroll(scrollView.FOCUS_DOWN);
        } });

答案 1 :(得分:0)

您可以使用array_方法完成大量工作(代码中的注释中的详细信息)......

public function getPrefixAttribute()
{
    $str=$this->attributes['Subject_name'];
    // Use uppercase list of words to exclude
    $exclude=array('AND', 'OF', 'IN');
    // Split string into words (uppercase)
    $current = explode(" ", strtoupper($str));
    // Return the difference between the string words and excluded
    // Use array_filter to remove empty elements
    $remain = array_filter(array_diff($current, $exclude));

    $ret = '';
    foreach ($remain as $word)
    {
        $ret .= $word[0];
    }
    return $ret;
}

使用array_filter()删除所有空元素,这些可能导致[0]部分失败,无论如何都无用。如果你有双重空格会发生这种情况,因为它会假设一个空元素。

答案 2 :(得分:0)

另一种方法是使用内置的PHP函数: -

function getPrefixAttribute() {
    $str = $this->attributes['Subject_name']; // 'data Structures And algorithms';
    $exclude = array('and', 'of', 'in'); // make sure to set all these to lower case
    $exploded = explode(' ', strtolower($str));

    // get first letter of each word from the cleaned array(without excluded words)
    $expected_letters_array = array_map(function($value){
        return $value[0];
    }, array_filter(array_diff($exploded, $exclude)));

    return strtoupper(implode('', $expected_letters_array));
}

答案 3 :(得分:0)

不可见的字符是&#39; / n&#39;,&#39; / r&#39;,&#39; / t&#39; 和手动删除它们的方法是

$string = trim(preg_replace('/\s\s+/', ' ', $string));
相关问题