Php bir diziye karmaşık bir dize dönüştürme

4 Cevap php

Ben toplama ihtiyacı bir form gelen bir php değişkeni var. Ben size yardımcı olabilir umuyoruz.

The variable contains a list of items (possibly two or three word items with a space in between words). I want to convert it to a comma separated list with no superfluous white space. I want the divisions to fall only at commas, semi-colons or new-lines. Blank cannot be an item.

İşte kapsamlı bir örnek (kasten dağınık girişi ile) bulunuyor:

Variable In: "dog, cat         ,car,tea pot,,  ,,, ;;(++NEW LINE++)fly,     cake"
Variable Out "dog,cat,car,tea pot,fly,cake"

Herkes yardımcı olabilir?

4 Cevap

Daha sonra "yararlı" preg_split ile parçaları, ve, implode {[(4)] içine splitting the string başlayabilirsiniz }:

$str_in = "dog, cat         ,car,tea pot,,  ,,, ;;
fly,     cake";

$parts = preg_split('/[,;\s]/', $str_in, -1, PREG_SPLIT_NO_EMPTY);

$str_out = implode(',', $parts);

var_dump($parts, $str_out);

(Here, the regex will split on ', ',' ; 've' \s ', herhangi bir boşluk karakteri anlamına gelir - ve biz sadece) boş olmayan parçaları tutmak

Için, alacak $parts:

array
  0 => string 'dog' (length=3)
  1 => string 'cat' (length=3)
  2 => string 'car' (length=3)
  3 => string 'tea' (length=3)
  4 => string 'pot' (length=3)
  5 => string 'fly' (length=3)
  6 => string 'cake' (length=4)

Ve için $str_out,

string 'dog,cat,car,tea,pot,fly,cake' (length=28)



Edit after the comment : Üzgünüm, ben bir fark etmedi ^ ^

Herhalde ([{kullanarak, ',' veya ';', parçalar üzerinde yineleme tarafından bölünmüş olurdu :-( Bu durumda, beyaz boşluk ile bölemezsiniz 2)]} her öğenin başında ve sonunda beyaz-karakterleri kaldırmak ve sadece boş olmadığını bu tutmak için:

$useful_parts = array();
$parts = preg_split('/[,;]/', $str_in, -1, PREG_SPLIT_NO_EMPTY);
foreach ($parts as $part) {
    $part = trim($part);
    if (!empty($part)) {
        $useful_parts[] = $part;
    }
}
var_dump($useful_parts);


Executing this portion of code gets me :

array
  0 => string 'dog' (length=3)
  1 => string 'cat' (length=3)
  2 => string 'car' (length=3)
  3 => string 'tea pot' (length=7)
  4 => string 'fly' (length=3)
  5 => string 'cake' (length=4)


And imploding all together, I get, this time :

string 'dog,cat,car,tea pot,fly,cake' (length=28)

Hangisi daha iyidir ;-)

Sen explode kullanın ve trim ve str_replace dizisini almak için, el ile özel karakterleri kaldırın ve sonra tekrar bir diziye çevirmek olabilir.

function getCleanerStringFromString($stringIn) {
	///turn the string into an array with a comma as the delimiter
	$myarray = explode(",",$stringin);

	for ($ii =0; $ii < count($myarray); $ii++) {
		///remove new lines, semi colons, etc
		///use this line as many times as you'd like to take out characters
		$myarray($ii) = str_replace(";","",$myarray($ii);


		////remove white spaces
		$myarray($ii) = trim($myarray($ii));

	}

	//then turn it back into an array:
	$backstring = implode(","$myarray);

	return $backstring;
}

Grep sonra bölünmüş, beklenen çıkışını vermek gibi görünüyor:

$array = preg_split('/\s*[;,\n]\s*/', $string);
$array = preg_grep('/^\s*$/', $array, PREG_GREP_INVERT);
$string = implode(',', $array);

EDIT: Aslında grep gerekli değildir:

$array = preg_split('/\s*[;,\n]\s*/', $string, -1, PREG_SPLIT_NO_EMPTY);
$string = implode(',', $array);

Sonra kalan sondaki / öndeki boşlukları kırparak, ilk-zA-Z0-9 (ve uzay) değil, tüm karakterleri eşleştirme, bu dizi boyunca yürümek, virgül üzerindeki tüm dizeyi patlayabilir. Eğer boşsa, diziden öğeyi unset. Geri bir dize patlar.

İdeal olarak, bu, sadece daha karışık karakter sağlar; \ s \ n vb

$strIn = "dog, cat         ,car,tea pot,,  ,,, ;;(++NEW LINE++)fly,     cake";
$firstArray = explode(",", $strIn);

$searchPattern = "/[^A-Za-z0-9 ]+/";

function removeViolators($item, $key) {
    preg_replace($searchPattern, "", $item);
    trim($item);
    if (empty($item)) {
        unset($item);
    }
}

array_walk($firstArray, removeViolators);
$strOut = implode(",", $firstArray);