여러 개의 공백 제거
나 이제...$row['message']
MySQL 데이터베이스에서 다음과 같은 모든 공백을 제거해야 합니다.\n
\t
기타 등등.
$row['message'] = "This is a Text \n and so on \t Text text.";
의 포맷은 다음과 같습니다.
$row['message'] = 'This is a Text and so on Text text.';
나는 시도했다.
$ro = preg_replace('/\s\s+/', ' ',$row['message']);
echo $ro;
하지만 제거는 되지 않습니다.\n
또는\t
, 1개의 공간만 사용합니다.어떻게 하는지 아는 사람 있어요?
필요한 것은 다음과 같습니다.
$ro = preg_replace('/\s+/', ' ', $row['message']);
사용하고 있습니다.\s\s+
공백(스페이스, 탭 또는 줄 바꿈) 뒤에 하나 이상의 공백이 표시됩니다.즉, 사실상 두 개 이상의 공백을 하나의 공백으로 대체해야 합니다.
원하는 것은 하나 이상의 공백을 단일 공백으로 바꾸면 패턴을 사용할 수 있습니다.\s\s*
또는\s+
(권장)
<?php
$str = "This is a string with
spaces, tabs and newlines present";
$stripped = preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $str);
echo $str;
echo "\n---\n";
echo "$stripped";
?>
이 출력은
This is a string with
spaces, tabs and newlines present
---
This is a string with spaces, tabs and newlines present
preg_replace('/[\s]+/mu', ' ', $var);
\s
에는 이미 탭과 새 행이 포함되어 있으므로 위의 regex로도 충분합니다.
1개의 기능으로 심플화:
function removeWhiteSpace($text)
{
$text = preg_replace('/[\t\n\r\0\x0B]/', '', $text);
$text = preg_replace('/([\s])\1+/', ' ', $text);
$text = trim($text);
return $text;
}
다뉴엘 오닐의 답변에 근거합니다.
$str='This is a Text \n and so on Text text.';
print preg_replace("/[[:blank:]]+/"," ",$str);
여기서 문제를 재현할 수 없습니다.
$x = "this \n \t\t \n works.";
var_dump(preg_replace('/\s\s+/', ' ', $x));
// string(11) "this works."
단순한 문자 변환 오류인지 아닌지는 모르겠지만, 이 예에서는 따옴표로 묶인 문자열을 사용하고 있습니다. \n
그리고.\t
는 이중 따옴표로 묶인 문자열이 있는 경우에만 새 행 및 탭으로 처리됩니다.즉, 다음과 같습니다.
'\n\t' != "\n\t"
편집: Codaddict가 지적한 바와 같이\s\s+
탭 문자를 하나만 대체하지 않습니다.아직 안 쓸 것 같아\s+
효율적인 솔루션이지만, 그 대신 다음과 같이 하는 것은 어떻습니까?
preg_replace('/(?:\s\s+|\n|\t)/', ' ', $x);
preg_replace('/(\s\s+|\t|\n)/', ' ', $row['message']);
그러면 모든 탭, 모든 줄바꿈 및 여러 공간, 탭 및 줄바꿈의 모든 조합이 단일 공백으로 바뀝니다.
<?php
#This should help some newbies
# REGEX NOTES FROM DANUEL
# I wrote these functions for my own php framework
# Feel Free to make it better
# If it gets more complicated than this. You need to do more software engineering/logic.
# (.) // capture any character
# \1 // if it is followed by itself
# + // one or more
class whitespace{
static function remove_doublewhitespace($s = null){
return $ret = preg_replace('/([\s])\1+/', ' ', $s);
}
static function remove_whitespace($s = null){
return $ret = preg_replace('/[\s]+/', '', $s );
}
static function remove_whitespace_feed( $s = null){
return $ret = preg_replace('/[\t\n\r\0\x0B]/', '', $s);
}
static function smart_clean($s = null){
return $ret = trim( self::remove_doublewhitespace( self::remove_whitespace_feed($s) ) );
}
}
$string = " Hey yo, what's \t\n\tthe sc\r\nen\n\tario! \n";
echo whitespace::smart_clean($string);
preg_replace() 미적용
$str = "This is a Text \n and so on \t Text text.";
$str = str_replace(["\r", "\n", "\t"], " ", $str);
while (strpos($str, " ") !== false)
{
$str = str_replace(" ", " ", $str);
}
echo $str;
저는 다음과 같이 하겠습니다.
a. 다음 예시와 같이 큰따옴표를 사용합니다.
$row['message'] = "This is a Text \n and so on \t Text text.";
b. 여분의 공백을 제거하려면 다음을 사용합니다.
$ro = preg_replace('/\s+/', ' ', $row['message']);
echo $ro;
이것이 가장 빠른 해결책은 아닐지 모르지만, 최소한의 코드를 필요로 하며, 작동해야 한다고 생각합니다.단, mysql을 사용한 적이 없기 때문에 틀릴 수도 있습니다.
필요한 것은 다음과 같이 실행하는 것입니다.
echo preg_replace('/\s{2,}/', ' ', "This is a Text \n and so on \t Text text."); // This is a Text and so on Text text.
다음 코드와 패턴을 사용합니다.
preg_replace('/\\s+/', ' ',$data)
$data = 'This is a Text
and so on Text text on multiple lines and with whitespaces';
$data= preg_replace('/\\s+/', ' ',$data);
echo $data;
http://writecodeonline.com/php/ 에서 테스트 할 수 있습니다.
사실 다음과 같은 것을 원한다고 생각한다면:
preg_replace('/\n+|\t+|\s+/',' ',$string);
그러면 여러 탭이 단일 탭으로 바뀝니다.
preg_replace("/\s{2,}/", "\t", $string);
preg_replace를 사용하지 않고 루프를 사용합니다.
<?php
$str = "This is a Text \n and so on \t Text text.";
$str_length = strlen($str);
$str_arr = str_split($str);
for ($i = 0; $i < $str_length; $i++) {
if (isset($str_arr[$i + 1])
&& $str_arr[$i] == ' '
&& $str_arr[$i] == $str_arr[$i + 1]) {
unset($str_arr[$i]);
}
else {
continue;
}
}
echo implode("", $str_arr) ;
?>
언급URL : https://stackoverflow.com/questions/2326125/remove-multiple-whitespaces
'programing' 카테고리의 다른 글
쿼리 빌더가 원시 SQL 쿼리를 문자열로 출력하려면 어떻게 해야 합니까? (0) | 2022.10.31 |
---|---|
MySQL: 선택문의 임시 열을 자동으로 증가시킵니다. (0) | 2022.10.31 |
MySQL 테이블에서 열을 삭제하는 방법 (0) | 2022.10.31 |
sql 쿼리를 선택하여 특정 사용자의 게시물, 팔로워 및 팔로워 수를 가져옵니다. (0) | 2022.10.31 |
jQuery를 사용하여 모바일 장치를 검색하는 방법 (0) | 2022.10.31 |