Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: zamiana stringa na array
Forum PHP.pl > Forum > PHP
Randallmaster
W jaki sposób poniższy string można zamienić na tablicę?

width: 500px; height: 500px; border-width: 5px; border-radius: 30px;

[width] => 500
[height] => 500
[border-width] => 5
itd.
questionmark.gif?
nospor
explode po sredniku
a potem kazdy element
explode po dwukropku


Mozna tez uzyc wyrazen regularnych, jak ktos je kojarzy
kpt_lucek
  1. // Tak na szybko
  2.  
  3. <?php
  4. $re = '/([a-z\-]+)\:\s([0-9]+px)/';
  5. $str = 'width: 500px; height: 500px; border-width: 5px; border-radius: 30px;';
  6.  
  7. preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
  8.  
  9. $data = [];
  10. array_walk($matches, function ($item) use (&$data) {
  11. $data[$item[1]] = $item[2];
  12. });
  13.  
  14. print_r($data);
Pyton_000
Dużo wad ma ten regexp.

Proszę banalna metoda zaczerpnięta z Stacka:
  1. function BreakCSS($CSS) {
  2. $results = array();
  3.  
  4. foreach(explode(';', $CSS) AS $attr)
  5. if (strlen(trim($attr)) > 0) // for missing semicolon on last element, which is legal
  6. {
  7. list($name, $value) = explode(':', $attr);
  8. $results[trim($name)] = trim($value);
  9. }
  10. return $results;
  11. }
trueblue
  1. $styles = "width: 500px; height: 500px; border-width: 5px; border-radius: 30px; background-image:url(\"aaa\")";
  2. $styles=str_replace(",\" \"","", "{\"" . strtr($styles, array(";"=>"\",\"",":"=>"\":\"","\""=>"'")) . "\"}");
  3. $json = json_decode($styles, true);
  4. $keys = array_map('trim', array_keys($json));
  5. $data = array_map('trim', $json);
  6. $result = array_combine($keys, $data);
  7. print_r($result);


//poprawione.
Pyton_000
; na końcu wysypuje skrypt, więc trzeba zadbać o to żeby go tam nie było.
trzczy
array_walk II smile.gif

  1. <?php
  2. $str = 'width: 500px; height: 500px; border-width: 5px; border-radius: 30px;';
  3. $array2 = preg_split('/([\s;:]+)/', $str);
  4. $array2, function ($el) use (&$array, &$key) {
  5. if ($key) {
  6. $array[$key] = $el;
  7. $key = null;
  8. } else $key = $el;
  9. }
  10. );
  11. print_r($array);
trueblue
Wszystkie powyższe metody wykładają się, jeśli pojawi się: background-image:url(http://domena.pl/aaa.jpg)
viking
https://github.com/sabberworm/PHP-CSS-Parser
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.