복붙노트

문자열에서 모든 특수 문자 제거 [duplicate]

PHP

문자열에서 모든 특수 문자 제거 [duplicate]

나는 URL에 관한 문제에 직면하고있다. 나는 무엇이든 포함 할 수있는 제목을 변환하고 모든 특수 문자를 제거하여 문자와 숫자 만 가질 수 있기를 원한다. 물론 공백을 하이픈으로 대체하고 싶다.

어떻게이 일을 끝낼 수 있습니까? 정규 표현식 (정규식)이 사용되는 것에 대해 많이 들었습니다 ...

해결법

  1. ==============================

    1.쉬워요:

    쉬워요:

    function clean($string) {
       $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
    
       return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
    }
    

    용법:

    echo clean('a|"bc!@£de^&$f g');
    

    출력 : abcdef-g

    편집하다:

    function clean($string) {
       $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
       $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
    
       return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
    }
    
  2. ==============================

    2.아래 해결책은 "SEO 친숙한"버전입니다.

    아래 해결책은 "SEO 친숙한"버전입니다.

    function hyphenize($string) {
        $dict = array(
            "I'm"      => "I am",
            "thier"    => "their",
            // Add your own replacements here
        );
        return strtolower(
            preg_replace(
              array( '#[\\s-]+#', '#[^A-Za-z0-9\. -]+#' ),
              array( '-', '' ),
              // the full cleanString() can be downloaded from http://www.unexpectedit.com/php/php-clean-string-of-utf8-chars-convert-to-similar-ascii-char
              cleanString(
                  str_replace( // preg_replace can be used to support more complicated replacements
                      array_keys($dict),
                      array_values($dict),
                      urldecode($string)
                  )
              )
            )
        );
    }
    
    function cleanString($text) {
        $utf8 = array(
            '/[áàâãªä]/u'   =>   'a',
            '/[ÁÀÂÃÄ]/u'    =>   'A',
            '/[ÍÌÎÏ]/u'     =>   'I',
            '/[íìîï]/u'     =>   'i',
            '/[éèêë]/u'     =>   'e',
            '/[ÉÈÊË]/u'     =>   'E',
            '/[óòôõºö]/u'   =>   'o',
            '/[ÓÒÔÕÖ]/u'    =>   'O',
            '/[úùûü]/u'     =>   'u',
            '/[ÚÙÛÜ]/u'     =>   'U',
            '/ç/'           =>   'c',
            '/Ç/'           =>   'C',
            '/ñ/'           =>   'n',
            '/Ñ/'           =>   'N',
            '/–/'           =>   '-', // UTF-8 hyphen to "normal" hyphen
            '/[’‘‹›‚]/u'    =>   ' ', // Literally a single quote
            '/[“”«»„]/u'    =>   ' ', // Double quote
            '/ /'           =>   ' ', // nonbreaking space (equiv. to 0x160)
        );
        return preg_replace(array_keys($utf8), array_values($utf8), $text);
    }
    

    위의 기능에 대한 이론적 근거 (비효율적이라고 생각하는 이유는 아래에있는 것이 더 낫습니다)는 URL에 맞춤법 검사와 키워드 인식 기능이 명시 적으로 지정되지 않아야한다는 것입니다.

    고객의 편집증에서 오랜 시간을 잃은 후에 나는 결국 그들은 상상하지 못한다는 사실을 알아 냈습니다. 그들의 SEO 전문가는 "Viaggi Economy Perù"를 viaggi-economy-peru로 변환한다고보고했습니다. (이전의 "청소"는 UTF8 문자를 제거했으나 Bogotà는 bogot가되었고 Medellìn은 medelln이되었습니다).

    그 결과에 영향을 미치는 몇 가지 흔한 오자가 있었고, 나에게 의미가있는 유일한 설명은 URL이 압축 해제되고, 단어가 골라졌으며, 하나님을 운전하는 데 사용되어 어떤 순위 알고리즘을 알고 있는지입니다. 그리고 그 알고리즘은 분명히 UTF8로 정리 된 문자열을 제공 받았기 때문에 "Perù"는 "Per"대신 "Peru"가되었습니다. "Per"가 일치하지 않아 일종의 목에 걸렸습니다.

    UTF8 문자를 유지하고 맞춤법 오류를 대체하기 위해 아래의 더 빠른 함수가 위의보다 정확한 (?) 함수가되었습니다. 물론 $ dict는 손으로 맞춰야합니다.

    간단한 접근법 :

    // Remove all characters except A-Z, a-z, 0-9, dots, hyphens and spaces
    // Note that the hyphen must go last not to be confused with a range (A-Z)
    // and the dot, being special, is escaped with \
    $str = preg_replace('/[^A-Za-z0-9\. -]/', '', $str);
    
    // Replace sequences of spaces with hyphen
    $str = preg_replace('/  */', '-', $str);
    
    // The above means "a space, followed by a space repeated zero or more times"
    // (should be equivalent to / +/)
    
    // You may also want to try this alternative:
    $str = preg_replace('/\\s+/', '-', $str);
    
    // where \s+ means "zero or more whitespaces" (a space is not necessarily the
    // same as a whitespace) just to be sure and include everything
    

    % 20과 +가 실제로 공백이기 때문에 URL을 먼저 urldecode ()해야 할 수도 있습니다. "절대 % 20gonna % 20give % 20you % 20up"가 있으면 절대적이지 않을 것입니다. - 너 - 업, Never20gonna20give20you20up. 당신은 그것을 필요로하지 않을지도 모르지만, 나는 가능성을 말할 것이라고 생각했습니다.

    테스트 케이스와 함께 완성 된 기능 :

    function hyphenize($string) {
        return 
        ## strtolower(
              preg_replace(
                array('#[\\s-]+#', '#[^A-Za-z0-9\. -]+#'),
                array('-', ''),
            ##     cleanString(
                  urldecode($string)
            ##     )
            )
        ## )
        ;
    }
    
    print implode("\n", array_map(
        function($s) {
                return $s . ' becomes ' . hyphenize($s);
        },
        array(
        'Never%20gonna%20give%20you%20up',
        "I'm not the man I was",
        "'Légeresse', dit sa majesté",
        )));
    
    
    Never%20gonna%20give%20you%20up    becomes  never-gonna-give-you-up
    I'm not the man I was              becomes  im-not-the-man-I-was
    'Légeresse', dit sa majesté        becomes  legeresse-dit-sa-majeste
    

    UTF-8을 처리하기 위해 여기서 찾은 cleanString 구현을 사용했습니다. 성능 향상을 위해 여기에 함수를 단순화하고 래핑 할 수 있습니다.

    위의 함수는 또한 소문자로 변환을 구현하지만 그 맛입니다. 그렇게하는 코드는 주석 처리되었습니다.

  3. ==============================

    3.여기,이 기능을 체크 아웃 :

    여기,이 기능을 체크 아웃 :

    function seo_friendly_url($string){
        $string = str_replace(array('[\', \']'), '', $string);
        $string = preg_replace('/\[.*\]/U', '', $string);
        $string = preg_replace('/&(amp;)?#?[a-z0-9]+;/i', '-', $string);
        $string = htmlentities($string, ENT_COMPAT, 'utf-8');
        $string = preg_replace('/&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);/i', '\\1', $string );
        $string = preg_replace(array('/[^a-z0-9]/i', '/[-]+/') , '-', $string);
        return strtolower(trim($string, '-'));
    }
    
  4. from https://stackoverflow.com/questions/14114411/remove-all-special-characters-from-a-string by cc-by-sa and MIT license