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

how to filter out invisible characters from string

我从网上手动复制了一些项目粘贴到 txt 中,然后将其存储到 database.Now 我错过的是不可见字符。

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

php代码-

public function getPrefixAttribute()
    {
        $str=$this->attributes['Subject_name'];
        $exclude=array('And', 'of','in');
        $ret = '';
        foreach (explode(' ', $str) as $word)
        {
            if(in_array($word, $exclude)) 
            {continue;}
            else{
            $ret .= strtoupper(substr($word,0,1));}
        }
    return $ret;
    }

输出-

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'

你快到了:

<?php
public function getPrefixAttribute()
{
    $str = $this->attributes[ 'Subject_name' ];

    // Make these uppercase for easier comparison
    $exclude = array( 'AND', 'OF', 'IN' );
    $ret = '';
    foreach( explode( ' ', $str ) as $word )
    {
        // This word should have a length of 1 or more or else $word[ 0 ] will fail
        // Check its uppercase version against  the $exclude array
        if( strlen( $word ) >= 1 && !in_array( strtoupper( $word ) , $exclude ) )
        {
            $ret.= strtoupper( $word[ 0 ] );
        }
    }
    return $ret;
}

您可以使用 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] 部分失败并且无论如何都没有用。如果你有双空格,就会发生这种情况,因为它会假定一个空元素。

另一种方法是使用内置 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));
}

不可见字符为'/n','/r','/t' 手动删除它们的方法是

$string = trim(preg_replace('/\s\s+/', ' ', $string));