PHP 변수에서 공백 공간을 제거하는 방법은 무엇입니까?
이 댓글은 PHP.net에서 알고 있습니다.나는 다음과 같은 비슷한 도구를 갖고 싶습니다.tr의 경우 실행할 수 .
tr -d " " ""
는 그 하지 못했다.php_strip_whitespace에 의해
$tags_trimmed = php_strip_whitespace($tags);
regex 기능도 실행할 수 없습니다.
$tags_trimmed = preg_replace(" ", "", $tags);
공백을 제거하려면 정규식을 사용할 수 있습니다.
$str=preg_replace('/\s+/', '', $str);
UTF-8 문자열의 공백을 처리할 수 있는 것에 대해서는, 이 회답도 참조해 주세요.
디폴트로는 정규 표현에서는 UTF-8 문자는 고려되지 않습니다.\s집합의 .는 탭,및 새 합니다.
// http://stackoverflow.com/a/1279798/54964
$str=preg_replace('/\s+/', '', $str);
가 되면 이 실패하거나 UTF-8은 .\s설명할 수 없습니다.
Unicode/utf-8에 도입된 새로운 유형의 공백에 대처하려면 보다 광범위한 문자열이 필요합니다.
로는 정규 가 다른 문자로 할 수.\x80 quad set을 할 수 .\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, en space, em space, em space, em space, 6 per em space, 숫자 공간, 구두점 공간, 얇은 공간, 머리털 공간, 제로 폭, 제로 폭의 결합자], 라인 구분자, 단락 구분자, 좁은 간격, 수학 매체l 공간, 단어 결합자, 표의 공간 및 제로 폭의 구분 없는 공간.
이들 대부분은 자동화된 툴이나 사이트에서 내보냈을 때 xml 파일에 대혼란을 일으키며 텍스트 검색과 인식을 망치고 보이지 않게 PHP 소스 코드에 붙여넣을 수 있습니다.이것에 의해, 파서는 다음의 커맨드(문단과 행 구분자)로 점프해, 코드 행을 건너뛰게 되어, 간헐적이고 설명할 수 없는 에러가 발생합니다.ave는 '문자 그대로 전염되는 질병'이라고 언급하기 시작했다
[웹에서 복사하여 붙여넣는 것은 더 이상 안전하지 않습니다.문자 스캐너를 사용하여 코드를 보호합니다.lol]
연속된 공백을 삭제해야 할 수 있습니다.다음과 같이 할 수 있습니다.
$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
4, 파일: PHP 4,5,7
문서: http://php.net/manual/en/function.trim.php
$tag에서 모든 화이트스페이스를 삭제하려면 다음 절차를 따릅니다.
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:// protocol에서 래퍼와 함께 파일 기능을 사용합니다(include, require 등에 사용할 수도 있습니다).
global $__myVar;
$__myVar = 'Enter tags here';
$data = php_strip_whitespace('var://__myVar');
주의: 글로벌 범위(글로벌 $_myVar 등)에 변수를 포함시키는 것을 잊지 마십시오.
오래된 게시물이지만 여기에 가장 짧은 답변이 나열되지 않아 지금 추가합니다.
strtr($str,[' '=>'']);
"이 고양이 가죽을 벗기는" 또 다른 일반적인 방법은 폭발물을 사용하여 이렇게 폭발시키는 것입니다.
implode('',explode(' ', $str));
하면 .ereg_replace
$str = 'This Is New Method Ever';
$newstr = ereg_replace([[:space:]])+', '', trim($str)):
echo $newstr
// Result - ThisIsNewMethodEver
, 「」를 사용합니다.preg_replace_callback 이 함수와 . 그리고 이 함수는 형제 함수와 동일합니다.preg_replace단, 출력 조작 방법을 보다 상세하게 제어할 수 있는 콜백 함수를 사용할 수 있습니다.
$str = "this is a string";
echo preg_replace_callback(
'/\s+/',
function ($matches) {
return "";
},
$str
);
$string = trim(preg_replace('/\s+/','',$string));
오래된 포스트이지만 다음과 같이 할 수 있습니다.
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;
HTML 엔티티에서는 표준 trim() 함수가 문제가 될 수 있습니다.그래서 이 문제에 대처하기 위해 사용하는 "슈퍼 트림" 기능을 썼고, 스트링의 시작, 끝 또는 부스 쪽에서 트리밍을 선택할 수 있습니다.
전체 문자열에서 공백을 제거하는 간단한 방법은 폭발 기능을 사용하고 for 루프를 사용하여 전체 문자열을 인쇄하는 것입니다.
$text = $_POST['string'];
$a=explode(" ", $text);
$count=count($a);
for($i=0;$i<$count; $i++){
echo $a[$i];
}
\s regex 인수는 UTF-8 멀티바이트 문자열과 호환되지 않습니다.
이 PHP RegEx는 UTF-8 스트링의 대체로서 PCRE(Perl Compatible Regular Expressions) 기반의 인수를 사용하여 이 문제를 해결하기 위해 작성한 것입니다.
function remove_utf8_whitespace($string) {
return preg_replace('/\h+/u','',preg_replace('/\R+/u','',$string));
}
- 사용 예 -
이전:
$string = " this is a test \n and another test\n\r\t ok! \n";
echo $string;
this is a test
and another test
ok!
echo strlen($string); // result: 43
그 후:
$string = remove_utf8_whitespace($string);
echo $string;
thisisatestandanothertestok!
echo strlen($string); // result: 28
PCRE 인수 목록
출처 : https://www.rexegg.com/regex-quickstart.html
Character Legend Example Sample Match
\t Tab T\t\w{2} T ab
\r Carriage return character see below
\n Line feed character see below
\r\n Line separator on Windows AB\r\nCD AB
CD
\N Perl, PCRE (C, PHP, R…): one character that is not a line break \N+ ABC
\h Perl, PCRE (C, PHP, R…), Java: one horizontal whitespace character: tab or Unicode space separator
\H One character that is not a horizontal whitespace
\v .NET, JavaScript, Python, Ruby: vertical tab
\v Perl, PCRE (C, PHP, R…), Java: one vertical whitespace character: line feed, carriage return, vertical tab, form feed, paragraph or line separator
\V Perl, PCRE (C, PHP, R…), Java: any character that is not a vertical whitespace
\R Perl, PCRE (C, PHP, R…), Java: one line break (carriage return + line feed pair, and all the characters matched by \v)
태그 형식의 공백에는 몇 가지 특별한 유형이 있습니다.를 사용해야 합니다.
$str=strip_tags($str);
용장 태그, 에러 태그를 삭제하고, 우선 통상의 문자열에 액세스 합니다.
그리고 사용
$str=preg_replace('/\s+/', '', $str);
나한텐 일인데.
언급URL : https://stackoverflow.com/questions/1279774/how-can-strip-whitespaces-in-phps-variable
'source' 카테고리의 다른 글
| HTML Collection 요소의 루프용 (0) | 2023.02.04 |
|---|---|
| Fedora 19 명령줄에서 데이터베이스 다이어그램을 생성하려면 어떻게 해야 합니까? (0) | 2023.02.04 |
| query_cache_size, Qcache_total_blocks 및 query_alloc_block_size (0) | 2023.02.04 |
| Google MAP API Uncatched TypeError: null의 속성 'offsetWidth'를 읽을 수 없습니다. (0) | 2023.02.04 |
| mariadb on fedora의 기본 비밀번호는 무엇입니까? (0) | 2023.02.04 |