Development Tip

PHP 변수에서 공백을 제거하려면 어떻게해야합니까?

yourdevel 2020. 10. 22. 22:59
반응형

PHP 변수에서 공백을 제거하려면 어떻게해야합니까?


주석 PHP.net을 알고 있습니다. tr간단히 실행할 수 있도록 PHP와 유사한 도구를 갖고 싶습니다.

tr -d " " ""

나는 성공적으로 기능 php_strip_whitespace실행하지 않습니다 .

$tags_trimmed = php_strip_whitespace($tags);

정규식 기능도 성공적으로 실행하지 못했습니다.

$tags_trimmed = preg_replace(" ", "", $tags);

정규식은 기본적으로 UTF-8 문자를 고려하지 않습니다. \s메타 문자는 원래 라틴어 세트를 차지한다. 따라서 다음 명령은 탭, 공백, 캐리지 리턴 및 새 줄만 제거합니다.

// http://stackoverflow.com/a/1279798/54964
$str=preg_replace('/\s+/', '', $str);

UTF-8이 주류가됨에 따라이 표현은 새로운 utf-8 문자에 도달하면 더 자주 실패 / 중단되어 설명 \s할 수없는 공백을 남겨 둡니다 .

unicode / utf-8에 도입 된 새로운 유형의 공백을 처리하려면 현대 공백을 일치시키고 제거하는 데 더 광범위한 문자열이 필요합니다.

기본적으로 정규식은 멀티 바이트 문자를 인식하지 않기 때문에 구분 된 메타 문자열 만 사용하여 식별 할 수 있습니다.이를 통해 바이트 세그먼트가 다른 utf-8 문자에서 변경되는 것을 방지 할 수 있습니다 ( \x80쿼드 세트에서 모든 \x80하위 바이트를 대체 할 수 있음). 스마트 따옴표)

$cleanedstr = preg_replace(
    "/(\t|\n|\v|\f|\r| |\xC2\x85|\xc2\xa0|\xe1\xa0\x8e|\xe2\x80[\x80-\x8D]|\xe2\x80\xa8|\xe2\x80\xa9|\xe2\x80\xaF|\xe2\x81\x9f|\xe2\x81\xa0|\xe3\x80\x80|\xef\xbb\xbf)+/",
    "_",
    $str
);

이렇게하면 탭, 줄 바꿈, 세로 탭, 용지 공급, 캐리지 리턴, 공백 및 여기 에서 추가로 제거 됩니다 .

다음 줄, 줄 바꿈하지 않는 공백, 몽골어 모음 구분 기호, [en quad, em quad, en space, em space, 3-per-em 공백, four-per-em 공백, 6-per-em 공백, 그림 공간, 구두점 공백 , 얇은 공간, 머리카락 공간, 0 너비 공백, 0 너비 비 결합 자, 0 너비 결합 자], 줄 구분 기호, 단락 구분 기호, 좁은 비 분리 공백, 중간 수학적 공간, 단어 결합 자, 표의 문자 공간 및 너비 0 비 깨는 공간.

텍스트 검색, 인식을 방해하는 자동화 된 도구 또는 사이트에서 내보낼 때 이러한 많은 부분이 xml 파일에 혼란을 일으켜 파서 가 다음 명령 (단락 및 줄 구분 기호)으로 이동하여 줄 을 발생시키는 PHP 소스 코드에 보이지 않게 붙여 넣을 수 있습니다. "텍스트 전송 질병"이라고 부르기 시작한 간헐적이고 설명 할 수없는 오류가 발생하는 코드를 건너 뛸 수 있습니다.

[웹에서 복사하여 붙여 넣는 것은 더 이상 안전하지 않습니다. 문자 스캐너를 사용하여 코드를 보호하십시오. ㅋㅋ]


스트립에 있는 공백을, 당신은 정규 표현식을 사용할 수 있습니다

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

UTF-8 문자열에서 공백을 처리 할 수있는 것에 대해서는 this answer 도 참조하십시오 .


연속 된 공백을 삭제해야하는 경우가 있습니다. 다음과 같이 할 수 있습니다.

$str = "My   name    is";
$str = preg_replace('/\s\s+/', ' ', $str);

산출:

My name is

$string = str_replace(" ", "", $string);

나는 preg_replace가 다음과 같은 것을 찾을 것이라고 믿습니다. [:space:]


PHP의 트림 기능을 사용하여 양쪽 (왼쪽 및 오른쪽)을 트림 할 수 있습니다.

 trim($yourinputdata," ");

또는

trim($yourinputdata);

당신은 또한 사용할 수 있습니다

ltrim() - Removes whitespace or other predefined characters from the left side of a string
rtrim() - Removes whitespace or other predefined characters from the right side of a string

시스템 : PHP 4,5,7
문서 : http://php.net/manual/en/function.trim.php


$ tags에서 모든 공백을 제거하려면 다음과 같이하십시오.

str_replace(' ', '', $tags);

새 줄을 제거하려면 조금 더 필요합니다.


가능한 모든 옵션은 변수를 파일로 시뮬레이션하기 위해 사용자 정의 파일 래퍼를 사용하는 것입니다. 다음을 사용하여 달성 할 수 있습니다.

1) 우선, 래퍼를 등록하십시오 (파일에서 한 번만 사용하십시오. session_start ()와 같이 사용하십시오).

stream_wrapper_register('var', VarWrapper);

2) 그런 다음 래퍼 클래스를 정의합니다 (정말 빠르지 만 완전히 정확하지는 않지만 작동합니다).

class VarWrapper {
  protected $pos = 0;
  protected $content;
  public function stream_open($path, $mode, $options, &$opened_path) {
    $varname = substr($path, 6);
    global $$varname;
    $this->content = $$varname;
    return true;
  }
  public function stream_read($count) {
    $s = substr($this->content, $this->pos, $count);
    $this->pos += $count;
    return $s;
  }
  public function stream_stat() {
    $f = fopen(__file__, 'rb');
    $a = fstat($f);
    fclose($f);
    if (isset($a[7])) $a[7] = strlen($this->content);
    return $a;
  }
}

3) 그런 다음 var : // 프로토콜에서 래퍼와 함께 파일 함수를 사용합니다 (include, require 등에도 사용할 수 있음).

global $__myVar;
$__myVar = 'Enter tags here';
$data = php_strip_whitespace('var://__myVar');

Note: Don't forget to have your variable in global scope (like global $__myVar)


You can do it by using ereg_replace

 $str = 'This Is New Method Ever';
 $newstr = ereg_replace([[:space:]])+', '',  trim($str)):
 echo $newstr
 // Result - ThisIsNewMethodEver

you also use preg_replace_callback function . and this function is identical to its sibling preg_replace except for it can take a callback function which gives you more control on how you manipulate your output.

$str = "this is a   string";

echo preg_replace_callback(
        '/\s+/',
        function ($matches) {
            return "";
        },
        $str
      );

Is old post but can be done like this:

if(!function_exists('strim')) :
function strim($str,$charlist=" ",$option=0){
    $return='';
    if(is_string($str))
    {
        // Translate HTML entities
        $return = str_replace(" "," ",$str);
        $return = strtr($return, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));
        // Choose trim option
        switch($option)
        {
            // Strip whitespace (and other characters) from the begin and end of string
            default:
            case 0:
                $return = trim($return,$charlist);
            break;
            // Strip whitespace (and other characters) from the begin of string 
            case 1:
                $return = ltrim($return,$charlist);
            break;
            // Strip whitespace (and other characters) from the end of string 
            case 2:
                $return = rtrim($return,$charlist);
            break;

        }
    }
    return $return;
}
endif;

Standard trim() functions can be a problematic when come HTML entities. That's why i wrote "Super Trim" function what is used to handle with this problem and also you can choose is trimming from the begin, end or booth side of string.


A simple way to remove spaces from the whole string is to use the explode function and print the whole string using a for loop.

 $text = $_POST['string'];
            $a=explode(" ", $text);
            $count=count($a);
            for($i=0;$i<$count; $i++){

                echo $a[$i];
            }

참고URL : https://stackoverflow.com/questions/1279774/how-can-strip-whitespaces-in-phps-variable

반응형